Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache.js is not rendering correctly

I'm using Mustache.js and I have the following template to render a drop-down list:

<select name="{{listName}}">
    {{#items}}
    <option value="{{id}}">{{name}}</option>
    {{/items}}
</select>

and the json object that I pass to the render method is:

items:[
    0: {id:1, name:Actor}
    1: {id:2, name:Director}
    2: {id:3, name:Producer}
    3: {id:4, name:Executive Producer}
    4: {id:5, name:Assistant Producer}
    5: {id:6, name:Scriptwriter}]
listName: "occupation"

the line that does the rendering is:

var html = Mustache.render(template, jsonData);

html variable contains:

<select name>
</select>

and what is rendered is an empty drop-down list. Though in Mustache demo page if i paste my template and the Json data it renders fine. Any idea what's going wrong?

like image 319
Khalid Dabjan Avatar asked Oct 04 '22 08:10

Khalid Dabjan


1 Answers

After research I have found what was going wrong. when logging the typeof the variable jsonData, it turned out to be a string and not an object.

So all I had to do is:

object = $.parseJSON(jsonData);
var html = Mustache.render(template, object);
like image 54
Khalid Dabjan Avatar answered Oct 08 '22 01:10

Khalid Dabjan