是否有通过对象属性循环的胡子/把手的方式?
所以,
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
}
然后,我可以在模板引擎中做一些等价的事情吗
for(var prop in o)
{
// with say, prop a variable in the template and value the property value
}
?
是否有通过对象属性循环的胡子/把手的方式?
所以,
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
}
然后,我可以在模板引擎中做一些等价的事情吗
for(var prop in o)
{
// with say, prop a variable in the template and value the property value
}
?
当前回答
这是@Ben的回答,更新后供Ember使用…注意你必须使用烬。get,因为context是作为String传入的。
Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
var newContext = Ember.get(this, context);
for(var prop in newContext)
{
if (newContext.hasOwnProperty(prop)) {
ret = ret + options.fn({property:prop,value:newContext[prop]});
}
}
return ret;
});
模板:
{{#eachProperty object}}
{{key}}: {{value}}<br/>
{{/eachProperty }}
其他回答
这是@Ben的回答,更新后供Ember使用…注意你必须使用烬。get,因为context是作为String传入的。
Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
var newContext = Ember.get(this, context);
for(var prop in newContext)
{
if (newContext.hasOwnProperty(prop)) {
ret = ret + options.fn({property:prop,value:newContext[prop]});
}
}
return ret;
});
模板:
{{#eachProperty object}}
{{key}}: {{value}}<br/>
{{/eachProperty }}
编辑:车把现在有一个内置的方式来完成这一点;见上面所选的答案。 当使用普通的胡子时,下面的建议仍然适用。
Mustache可以迭代数组中的项。所以我建议创建一个单独的数据对象,以Mustache可以使用的方式格式化:
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
if (o.hasOwnProperty(prop)){
mustacheFormattedData['people'].push({
'key' : prop,
'value' : o[prop]
});
}
}
现在,你的胡子模板将是这样的:
{{#people}}
{{key}} : {{value}}
{{/people}}
查看“非空列表”部分:https://github.com/janl/mustache.js
它实际上很容易作为一个helper来实现:
Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
for(var prop in context)
{
ret = ret + options.fn({property:prop,value:context[prop]});
}
return ret;
});
然后这样使用它:
{{#eachProperty object}}
{{property}}: {{value}}<br/>
{{/eachProperty }}
自Handlebars 1.0rc1以来的内置支持
Handlebars.js中已经添加了对该功能的支持,因此不再需要外部helper。
如何使用
数组:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
对象:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
注意,只有通过hasOwnProperty测试的属性才会被枚举。
@Amit的回答很好,因为它将工作在胡子和把手。
至于只有句柄的解决方案,我已经看到了一些,我喜欢https://gist.github.com/1371586上的each_with_key块帮助器。
它允许您迭代对象字面量,而不必首先重新构造它们 它让你控制你所谓的关键变量。在许多其他解决方案中,你必须小心使用名为“key”或“property”的对象键。