我使用Meteor的Blaze作为html模板,我有多个循环:
numbers = [0.0, 0.1, 0.29, 1.278, 59.0, 99.9]
for x in numbers:
print "{:05.2f}".format(x).replace(".","_")
我知道:
let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
let attrs = ['name', 'age']
{{#each objects}}
<h3>Object {{@index}}</h3>
{{#each attrs}}
[...] // code here
{{/each}}
{{/each}}
用于了解当前的循环索引(因此{{@index}}
[..]
是对attrs数组进行索引的引用{{@index}}
用于了解当前的循环值(因此{{this}}
[...]
为{{value}}
或name
)age
是对父循环值的引用(因此{{..}}
[...]
是第一个循环时的当前对象)现在,我希望{{..}}
[...]
循环的当前索引。我在谷歌和Stackoverflow上搜索了很多但没有找到。
答案 0 :(得分:3)
Huumm,有关Blaze的新闻允许new创建变量(使用#let)。一个简单的解决方案是:
let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
let attrs = ['name', 'age']
{{#each objects}}
{{#let object=this object_idx=@index}}
<h3>Object {{object_idx}}</h3>
{{#each attrs}}
Object idx {{object_idx}} | Object {{object}}
Attr idx {{@index}} | Attr {{this}}
{{/each}}
{{/let}}
{{/each}}
更新:您可以暂时执行{{#each object in objects}}
,避免您执行{{#let object=this}}
{{#each object in objects}}
{{#let object_idx=@index}}
<h3>Object {{object_idx}}</h3>
{{#each attr in attrs}}
Object idx {{object_idx}} | Object {{object}}
Attr idx {{@index}} | Attr {{attr}}
{{/each}}
{{/let}}
{{/each}}
答案 1 :(得分:2)
您需要为内循环创建一个帮助程序,如下所示:
Template.myTemplate.helpers({
value: function(){
return Template.parentData(1)[this];
}
});
Template.parentData(1)
从当前级别返回数据上下文一(1)级。 [this]
引用当前数据给出的该对象的键。