7

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?

0

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Gazler, yes that works! Is nested JSON object not recommend?
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.
Thank you! I've been at this for 2 days!
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
@Gazler You can also do var str = Mustache.to_html(template, data.pop()); for a more elegant solution :)
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.