Khalid Dabjan
Khalid Dabjan

Reputation: 2797

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?

Upvotes: 5

Views: 3437

Answers (2)

Khalid Dabjan
Khalid Dabjan

Reputation: 2797

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);

Upvotes: 3

skyboyer
skyboyer

Reputation: 23705

I have no idea why it has happened: demo page that you refer to uses Maustache.to_html method. That definitely works well:

document.getElementById('target').innerHTML =
    Mustache.to_html(document.getElementById('template').innerText, jsonData)

But at homepage of Javascript library .render() method is named.

Upvotes: 1

Related Questions