Take the 2-minute tour ×

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?

share|improve this question
add comment

2 Answers

up vote 8 down vote accepted

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);
share|improve this answer
Hi Gazler, yes that works! Is nested JSON object not recommend? –  nolabel Apr 1 '11 at 17:54
Nesting objects isn't a problem. Yours was nested in an array, which is why your example didn't work. If you do wish to nest arrays(lists) or objects then check out the "Dereferencing Section" section in the github.com/janl/mustache.js documentation. –  Gazler Apr 1 '11 at 17:56
Thank you! I've been at this for 2 days! –  nolabel Apr 1 '11 at 17:57
My json is generated by coldfusion. I tried to remove the outer brackets in cf but was unsuccessful so I ended up using data[0] in js. Thanks @Gazler –  dmitrymar Nov 16 '12 at 18:03
@Gazler You can also do var str = Mustache.to_html(template, data.pop()); for a more elegant solution :) –  ViniciusPires Jul 10 '13 at 22:19
add comment

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.

share|improve this answer
add comment

Your Answer


