为什么嵌套在模板中的每个内容都不输出任何内容

Why does nested each in template output nothing

本文关键字:任何内 输出 嵌套 为什么      更新时间:2023-09-26

虽然这是按预期呈现的:

{{#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}},也没有任何显示。

怎么了?

因为 #each 子句将数据上下文更改为当前项。

如果你想要每个Itemstypes的列表,你可以使用 .. 获取父数据上下文。

如果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.
  }
});
相关文章: