【问题标题】:How to access outer {{#each}} collection value in the nested loop如何在嵌套循环中访问外部 {{#each}} 集合值
【发布时间】:2012-11-21 03:27:19
【问题描述】:

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

我找到了一个similar question 用于内部事件处理程序访问的情况。

【问题讨论】:

  • 我想就是这样。究竟是什么问题?
  • 感谢您的评论。我发布这个问题是因为我对我的代码没有信心,也找不到为此目的的流星示例代码。我想知道是否有人知道更聪明的实现。
  • 这里有更好的方法,不需要上面的 registerHelper,下面的语法可以工作: Template.example.myHelper = function(outItem, inItem){ /* 可以通过 outItem 访问 outerCollection 项目 */ };

标签: meteor


【解决方案1】:

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

假设您有名为 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已经可用于模板,它的字段被拾取。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 但是如何在 js 中得到 {{aaa}} 呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多