How to get the index in meteor in each

时光毁灭记忆、已成空白 提交于 2019-12-24 07:03:38

问题


How to get the each loop index in meteor.@index is not working.Please help me.

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}} 

回答1:


It requires another helper, check out my solution that I have used in my book on Meteor:

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

This registers a global helper named withIndex. Whenever you call it on an array that is used inside the each context it will allow you to use {{index}} in the same way you would have used {{@index}} to tell which position in the array each element has.

Adjust your inclusion tag to pass api_rest_data to withIndex first:

{{#each withIndex api_rest_data}}



回答2:


Many thanks to Stephan for this intermediate solution. Here is my version; it allows for the variables {{index}} & {{value}} in the {{#each}} context.

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

BTW, the {{@index}} context as per Handlebars/Spacebars specification should be in a new Meteor release soon, according to this issue tracker.



来源:https://stackoverflow.com/questions/26758925/how-to-get-the-index-in-meteor-in-each

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!