1

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}} 
vamsi kr
  • 431
  • 1
  • 4
  • 13
  • http://stackoverflow.com/questions/13430455/using-index-in-meteor-each-iterator-doesnt-work – sdooo Nov 05 '14 at 14:29
  • possible duplicate of [In meteor is there a way to access array index in spacebars](http://stackoverflow.com/questions/21815713/in-meteor-is-there-a-way-to-access-array-index-in-spacebars) – David Weldon Nov 05 '14 at 20:24

2 Answers2

2

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}}
Stephan
  • 1,279
  • 8
  • 16
  • I believe this should be `UI.registerHelper` instead of `Template.registerHelper`. Other wise, I think this is an elegant solution. – Scalahansolo Nov 05 '14 at 19:29
  • 2
    The `UI` namespace was deprecated in [0.9.4](https://github.com/meteor/meteor/blob/devel/History.md#v094). [Template.registerHelper](https://docs.meteor.com/#/full/template_registerhelper) is now the correct function. – David Weldon Nov 05 '14 at 20:22
0

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.

cneuro
  • 968
  • 13
  • 17