I have a JSON array of objects, and am trying to work out how to display them in Mustache.js. The array can be variable in length and content.
Example:
[ Object { id="1219", 0="1219", title="Lovely Book ", url= "myurl} , Object { id ="1220" , 0="1220 , title "Lovely Book2" , url="myurl2"}]
Ive tried:
        $.getJSON('http://myjsonurl?type=json', function(data) {
        var template = $('#personTpl').html();
        var html = Mustache.to_html(template, data);
        $('#test').html(html);
and the template:
 <script id="personTpl" type="text/template">
TITLE: {{#data}} {{title}} IMAGE: {{image}}
<p>LINK: <a href="{{blogURL}}">{{type}}</a></p>  {{/data}} 
</script>
but that doesn't display anything.
I've tried putting the JSON into an array, and then accessing it directly using  products[1] something like this:
$.getJSON("http://myjsonurl?type=json", function(json) 
{
    var products = [];
    $.each(json, function(i, product)
    {           
            var product =
            {           
                Title:product.title,
                Type:product.type,
                Image:product.image             
            };
            products.push(product);
        ;       
    });     
    var template = "<h1>Title: {{ Title }}</h1> Type: {{ Type }} Image : {{ Image }}";
    var html = Mustache.to_html(template, products[1]);
    $('#json').html(html);                      
}); 
which will display one record fine, but how can I iterate over them and display all ?
You need a single JSON object that looks like:
var json = { id:"1220" , 0:"1220", title:"Lovely Book2", url:"myurl2" };
var template = $('#personTpl').html();
var html = Mustache.to_html(template, json);
$('#test').html(html);
So something like this should work:
$.getJSON('http://myjsonurl?type=json', function(data) {
var template = $('#personTpl').html();
$.each(data, function(key,val) {
        var html = Mustache.to_html(template, val);
        $('#test').append(html);
});
});
                        For your template to work the way you have it, your json needs to look like this
{
  "data": [
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"},
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"},
    { "id":"1219", "0":"1219", "title":"Lovely Book ", "url": "myurl"}
  ]
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With