虽然按预期呈现:
{{#each Items}} // a collection
{{title}}
{{/each}}
{{#each types}} // another ollection
{{refId}}
{{/each}}
如果我把它放在一起:
{{#each Items}}
{{title}}
{{#each types}}
{{refId}}
{{/each}}
{{/each}}
#each types
为空。
模板助手:
Template.menuItems.helpers({
restMenuItems: function() {
return RestMenuItems.find({restRefId: this._id}, {sort:Template.instance().sort.get()});
},
restMenuSideItems: function() {
return RestMenuSideItems.find({restRefId: this._id}, {sort:Template.instance().sort.get()});
}
});
Template.menuItems.onCreated( function(){
this.subscribe('restMenuItems');
this.subscribe('restMenuSideItems');
});
以及一些模板代码:
{{#each restMenuItems}}
<div>
<select class="list-group select_side_addons">
{{#each restMenuSideItems}}
<option>{{restRefId}}</option>
{{/each}}
</select>
</div>
{{/each}}
即使将{{#each restMenuSideItems}}
替换为{{#each ../restMenuSideItems}}
,也不会显示任何内容。
怎么了?
答案 0 :(得分:3)
因为#each
子句将数据上下文更改为当前项。
如果您希望每个types
中都包含Items
列表,则可以使用..
获取父数据上下文。
如果types
是父上下文的属性:
{{#each Items}}
{{title}}
{{#each ../types}}
{{refId}}
{{/each}}
{{/each}}
如果types
是模板助手,您可以将父上下文作为参数传递给它:
{{#each Items}}
{{title}}
{{#each types ..}}
{{refId}}
{{/each}}
{{/each}}
并使用上下文查询。
Template.myTemplate.helpers({
types: function(parent) {
// you now have the parent context here.
// use parent._id etc. where you used this._id in the
// "flat" version.
}
});