计数清单?

时间:2011-11-14 17:21:27

标签: mustache

我们来看看这个片段:

{{#repos}}
<b>{{name}}</b>
{{/repos}}

如何计算repos中的项目数?

2 个答案:

答案 0 :(得分:4)

一种方法是将逻辑添加到JSON本身作为this上的函数:

var tmpl = "{{#repos}}<b>{{name}}</b>{{/repos}}({{count}})";

var json = {
    repos: [{ name: "Tom"}, { name: "Dick"}, { name: "Harry"}],
    count: function() { return this.repos.length; }
};
alert(Mustache.to_html(tmpl, json));

http://jsfiddle.net/mblase75/QBzuk/

答案 1 :(得分:3)

至少对我来说,我能够使用&#34; .length&#34;函数直接如下:(使用Mustache v 0.8.1测试)

var tmpl = "{{#repos}}<b>{{name}}</b>{{/repos}} ({{repos.length}})";
var json = {
    repos: [{ name: "Tom"}, { name: "Dick"}, { name: "Harry"}]
};
alert(Mustache.to_html(tmpl, json));

警告&#34; <b>Tom</b><b>Dick</b><b>Harry</b> (3)&#34;