2012-03-12 195 views
6

我有一個JSON數組對象,並試圖找出如何在Mustache.js中顯示它們。該數組的長度和內容可以是可變的。鬍鬚,遍歷JSON對象

例子:

[ Object { id="1219", 0="1219", title="Lovely Book ", url= "myurl} , Object { id ="1220" , 0="1220 , title "Lovely Book2" , url="myurl2"}] 

我用盡:

 $.getJSON('http://myjsonurl?type=json', function(data) { 
     var template = $('#personTpl').html(); 
     var html = Mustache.to_html(template, data); 
     $('#test').html(html); 

和模板:

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

但不顯示任何內容。

我試圖把JSON到一個數組,然後訪問它直接使用products[1]是這樣的:

$.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);      

}); 

這將顯示一條記錄很好,但我怎麼能在它們之間迭代並顯示所有?

+0

這樣做是爲了循環,如果對象的數組是可變的內容不健全適合於模板 – maxbeatty 2012-03-15 07:05:37

回答

9

你需要一個JSON對象,看起來像:

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); 

所以這樣的事情應該工作:

$.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); 
}); 

}); 
+0

啊,不知道鬍鬚渲染必須在每個。謝謝! – BobFlemming 2012-03-13 09:40:14

+1

像這樣循環的鬍子效果很差 – maxbeatty 2012-03-15 07:06:27

+1

確實如此。上述答案是OP的問題,但遠沒有效率。更好的是通過例如{array:[{title:'one'},{title:'two'}]}然後,您可以在模板中使用它們:{{#array}}

{{title}}

{{/ array}} – StuR 2012-03-15 10:34:35

2

您的模板工作,你有它的方式,你的JSON需要看起來像這樣

{ 
    "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

這應該使得消除每個語句的需要

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); 

在你的模板,通過東西

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