问题
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