I have a list of objects in meteorjs which I am iterating in meteorjs templates like
{{#each objects}}
{{/each}}
In the template I want to print the number of the loop iteration. That is, if the length of the objects list is 100 I want to print the numbers from 1 to 100 in the template. How can I do this?
You can't do this at the moment without giving in an index in your helper, i.e
Template.yourtemplatename.object_with_index = function() {
var objects = Template.yourtemplatename.objects();
for(var i = 0; i=objects.length; i++) {
objects[i].index = i;
}
return objects;
}
Then do:
{{#each object_with_index}}
<p>This is number {{index}}</p>
{{/each}}
Not the prettiest way, but other variations would basically do the same thing under the hood (e.g if you used a map
)
If you objects is a cursor, you can use its map method:
Template.yourtemplatename.objects = YourCollection.find().map(function(document, index){
document.index = index;
return document;
});
I made a global helper that add an index to an array :
UI.registerHelper('addIndex', function(thatArray) {
if (thatArray && thatArray.length) {
$.each(thatArray, function (position, thatObject) {
thatObject.index = position;
thatArray[position] = thatObject;
});
return thatArray;
}
});
and then you call it like that :
{{#each addIndex arrayWithoutIndex}}
The current value is at this index number : {{index}}
{{/each}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With