问题 如何在嵌套循环中访问外部{{#each}}集合值


在循环中访问外部#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
});

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


11175
2017-12-03 16:02


起源

我想就是这样。究竟是什么问题? - Tom Coleman
谢谢你的评论。我发布这个问题是因为我对我的代码没有信心而且为此目的找不到流星样本代码。我想知道是否有人知道更聪明的实施。 - hyde
这里有更好的方法,不需要registerHelper,如下所示,以下语法可以工作:Template.example.myHelper = function(outItem,inItem){/ *可以通过outItem * /}访问outerCollection项; - hyde
这也可能有所帮助:[stackoverflow.com/questions/13789622/...        [1]: stackoverflow.com/questions/13789622/... - zorlak


答案:


我想你自己已经回答了这个问题!运用 ../ 记录在案 https://github.com/meteor/meteor/wiki/Handlebars


12
2017-12-14 00:52



但是你怎么在js中获得{{aaa}}? - kpie


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

假设你有一个名为as的集合 Collection.Customer 和 Collection.RechargePlan 并且您在模板中使用它们来更新Customer。

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,../实际上比heirarchy高出一步,然后访问该字段(如果可用),因为Customer已经可用于模板,它的字段被拾取。


2
2018-05-14 12:27