2011-06-09 57 views
8

我使用Mustache.js succusefully顯示HTML,這裏的代碼如果對象在數組中,如何使用Mustache.js?

 var mygame = { 
     player:'viking', 
     games:[{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}] 
     }; 
    var template = '{{player}} is a good guy<br/> <ul>{{#games}}<li>name:{{name}} and type:{{type}} </li>{{/games}}</ul>'; 
    var html = Mustache.to_html(template, mygame); 
    var con = document.getElementById('container'); 
    con.innerHTML = html; 

但我怎麼使用它時,對象是一個數組,像

var mygames = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]; 

回答

8

試試這個:

var mygames = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]; 

var mygame = { 
    player: 'viking', 
    games: mygames 
} 
var template = '{{player}} is a good guy<br /> <ul>{{#games}}<li>name:{{name}} and type:{{type}} </li>{{/games}}</ul>'; 
var html = Mustache.to_html(template, mygame); 
var con = document.getElementById('container'); 
con.innerHTML = html; 
+3

Mustache.js不能使用數組作爲參數?我不想將我的數組包裹在對象中 – vikingmute 2011-06-10 01:47:04

2

你需要這樣做:

var mygames = {games: [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]}; 

var template= "{{#games}} Player name: {{name}} Type: {{type}}{{/games}}"; 

var html = Mustache.to_html(template, mygames); 
var con = document.getElementById('container'); 
con.innerHTML = html; 

或簡單地遍歷mygames對象,並追加HTML

var html=""; 
var template= "Player name: {{name}} Type: {{type}};" 
for (var i=0;i<mygames.length;i++) 
{ 
    html+=Mustache.to_html(template, mygames[i]); 
} 
var con = document.getElementById('container'); 
con.innerHTML = html; 

希望這有助於

35

你可以這樣說:

var model = [{name:'d1',type:'avg'},{name:'cod7',type:'fps'},{name:'war3',type:'rts'}]; 
var template = '<ul> {{#.}} <li>name:{{name}} and type:{{type}} </li> {{/.}} </ul>'; 
var html = Mustache.to_html(template, model); 
+0

+1,因爲這是最優雅的解決方案 – Frank 2012-08-26 18:21:50

+2

另一個答案只是提供避免這種情況的方法。因爲這表明鬍鬚語法實際上允許你使用一個數組作爲數據對象,而不用將它包裝在絨毛中,這應該是公認的答案。 – Semicolon 2013-03-20 21:01:59

+0

這應該是正確的答案! – vNext 2015-02-08 12:08:39

相關問題