11

在循环中访问外部#each 集合值的标准方法是什么?例如:

<template name="example">
  {{#each outerCollection}}
  <tr>
    {{#each innerCollection}}
      <td>{{aaa}}</td>
    {{/each}}
  </tr>
  {{/each}}
</template>

Template.example.aaa = function(){
  // cannot access outerCollection values
}

在上面的 Template.example.aaa 中,this指向内部集合。

我找不到访问 outerCollection 项目的方法。我的解决方案如下所示,我正在定义自己的辅助函数。这是实现此目的的标准 Meteor 方式吗?

<template name="example">
  {{#each outerCollection}}
  <tr>
    {{#each innerCollection}}
      <td>{{myHelper ../outerItem innerItem}}</td>
    {{/each}}
  </tr>
  {{/each}}
</template>

Handlebars.registerHelper('myHelper', function (outItem, inItem) {
  // can access outerCollection via outerItem
});

对于内部事件处理程序访问,我发现了一个类似的问题。

4

2 回答 2

12

我想你已经回答了这个问题!使用../记录在https://github.com/meteor/meteor/wiki/Handlebars中。

于 2012-12-14T00:52:46.797 回答
2

您可以使用下面的代码来获取外部集合。

假设您有名为Collection.CustomerCollection.RechargePlan的集合,并且您在模板中使用这两者来更新客户。

Customer = {"name":"James", "rechargeplan":"monthly"};
RechargePlan = [{"rechargeplan": "monthly"},{"rechargeplan": "yearly"}];

 //Inside template, Bydefault Customer is available.
{{#each RechargePlan}}
  {{#if equals ../rechargeplan rechargeplan}}
      //Hurray Plan matches
  {{/if}}
{{/each}}

在上面的代码中,../rechargeplan实际上是Customer.rechargeplan, ../ 实际上比层次结构高了一步,然后访问该字段(如果可用),因为 Customer 已经可用于模板,所以它的字段被拾取。

于 2016-05-14T12:27:02.980 回答