开发者

How to use Mustache.js if the JSON object is in a nested array?

开发者_C百科

I have heard wonderful things about Mustache and decided to give it a try.

I am trying to figure out how to use Mustache template with jQuery. I have been searching for a few days now.

Mustache can be found here: https://github.com/janl/mustache.js/

Here is my attempt:

$.getJSON('get_fullname.asp', {name: 'johnny'}, function(data, status, xhr) {

    var template = '<h1>{{NAME}}</h1><p>test</p>';
    strHTML = Mustache.to_html(template, data);
    $('#container').html( strHTML );

});

My JSON data returns [{"NAME":"John","MIDDLE":"A","LAST":"Smith"}]

All I get is <p>test</p>.

I've also tried using this template but still get <p>test</p>.

var template = '{{#NAME}}<h1>.</h1>{{/NAME}}<p>test</p>';

What am I missing?


At a glance, your JSON object seems to be nested in an array. Remove the [] around it and see if it works then. You can do this at a server level (which I recommend) or in the javascript by calling:

strHTML = Mustache.to_html(template, data[0]);

instead of:

strHTML = Mustache.to_html(template, data);


As a good practice, if you are not printing an array, the server shouldn't return that from your request.

Even if it's being serialized into JSON, to get this result, the source structure must be something like an array of an object or (like in PHP) an array of an associative array.

If what you really wanted was printing a list of names, you should iterate on "." like in this Fiddle: http://jsfiddle.net/viniciuspires/3e5cs/

{{#.}}
<li>{{last}}, {{name}}.</li>
{{/.}}

Which produces the same result for only one name, but extends the list as it gets more names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜