【问题标题】:How to get the index in meteor in each如何获取每个流星中的索引
【发布时间】:2015-03-04 02:42:53
【问题描述】:

如何获取流星中的每个循环索引。@index 不起作用。请帮助我。

Template.apichange.helpers({
    api_rest_data: function () 
    {     
        return Session.get("api_rest_list");
    }
   });




 {{#each api_rest_data}}
                    <tr>
                        <td><select id="methodname"> <option id="optn" value="{{ method_name }}"> {{ @index }}  </option></select></td>

                    </tr>
   {{/each}} 

【问题讨论】:

标签: meteor


【解决方案1】:

它需要另一个助手,查看我在 Meteor 书中使用的 my solution

Template.registerHelper('withIndex', function (list) {
    var withIndex = _.map(list, function (v, i) {
        v.index = i;
        return v;
    });
    return withIndex;
});

这会注册一个名为 withIndex 的全局帮助程序。每当您在 each 上下文中使用的数组上调用它时,它将允许您使用 {{index}},就像使用 {{@index}} 来判断每个元素在数组中的位置一样。

调整您的包含标签,首先将api_rest_data 传递给withIndex

{{#each withIndex api_rest_data}}

【讨论】:

  • 我认为这应该是UI.registerHelper 而不是Template.registerHelper。否则,我认为这是一个优雅的解决方案。
  • UI 命名空间在 0.9.4 中已弃用。 Template.registerHelper 现在是正确的函数。
【解决方案2】:

非常感谢 Stephan 提供的中间解决方案。这是我的版本;它允许在 {{#each}} 上下文中使用变量 {{index}}{{value}}

Template.registerHelper('withIndex', function (array) {
  return _.map(array, function (val, i) {
    return {
      'index': i,
      'value': val
    };
  });
});

顺便说一句,根据 this issue tracker,根据 Handlebars/Spacebars 规范的 {{@index}} 上下文应该很快就会出现在新的 Meteor 版本中。

【讨论】:

  • 好像合并了。
猜你喜欢
  • 2015-08-19
  • 2022-01-04
  • 1970-01-01
  • 2016-07-12
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多