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

javascriptjquerymustachetemplates

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?

Best Solution

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