我使用Mustache.js多次显示html,这是代码
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'}];
答案 0 :(得分: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);
答案 1 :(得分: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;
答案 2 :(得分: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;
希望这有帮助