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: .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?
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./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 edited Sep 23, 2011 at 8:26 Ikke 101k23 gold badges100 silver badges120 bronze badges asked Apr 1, 2011 at 17:37 nolabelnolabel 1,1573 gold badges18 silver badges26 bronze badges 02 Answers
Reset to default 8At 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 remend) 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/viniciuspires/3e5cs/
{{#.}}
<li>{{last}}, {{name}}.</li>
{{/.}}
Which produces the same result for only one name, but extends the list as it gets more names.