这是JSON:
var data = [
{
"event": {
"name": "txt1",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
},
{
"event": {
"name": "txt2",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
},
{
"event": {
"name": "txt3",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
}
];
我的胡子模板是:
{{#event}}
<div>
<h2>{{name}}</h2>
<span>on {{data}}</span>
<p>{{address}}</p>
</div>
{{/event}
所以上面的模板代码不起作用。我现在做的是做一个for
循环:
var html = "";
for(var i = 0; i < data.length; i++){
html += Mustache.to_html(tmp, data[i]);
}
任何更好的方法让它在没有任何循环的情况下工作?
答案 0 :(得分:4)
这里只有一种方法可以使用胡须模板。您按如下方式设置数据:
var data = {data: [
{
"event": {
"name": "txt1",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
},
{
"event": {
"name": "txt2",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
},
{
"event": {
"name": "txt3",
"data": "2011-01-02",
"address": "Guangzhou Tianhe Mall"
}
}
]};
,您的模板应如下所示:
{{data}}
{{#event}}
<div>
<h2>{{name}}</h2>
<span>on {{data}}</span>
<p>{{address}}</p>
</div>
{{/event}
{{/data}}
希望有所帮助