Mustache, iteration over JSON objects

I have an array of JSON objects, and I'm trying to figure out how to display them in Mustache.js. An 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 pattern:

  <script id="personTpl" type="text/template"> TITLE: {{#data}} {{title}} IMAGE: {{image}} <p>LINK: <a href="{{blogURL}}">{{type}}</a></p> {{/data}} </script> 

but it doesn’t display anything.

I tried to put JSON in an array and then accessed 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, but how can I iterate over them and display everything?

+6
source share
3 answers

You need one JSON object that looks like this:

 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); }); }); 
+9
source

For your template to work the way you need it, your json should 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"} ] } 
+2
source

This should eliminate the need to make every statement.

 var json = { id:"1220", 0:"1220", title:"Lovely Book2", url:"myurl2" }; var stuff = {stuff: json}; var template = $('#personTpl').html(); var html = Mustache.to_html(template, stuff); $('#test').html(html); 

In your template, do this to iterate over the material

 <script id="personTpl" type="text/template"> {{#stuff}} TITLE: {{title}} IMAGE: {{image}} <p>LINK: <a href="{{blogURL}}">{{type}}</a></p> {{/stuff}} </script> 
+2
source

Source: https://habr.com/ru/post/910528/


All Articles