I am using meteor Shark branch.
Is there a way to access array index inside each block helper in spacebars?
I am looking for something like this.
{{#each humans}}
{{this.arrayIndex}}
{{/each}}
Spacebars gained a lot of functionality in 1.2, including a native @index. Helpers are no longer needed to solve this problem - you can simply do this:
<template name="showHumans">
<ul>
{{#each humans}}
<li>{{@index}}: {{name}}</li>
{{/each}}
</ul>
</template>
I saw a similar example using template helpers in the meteor book in the "animations" chapter. You can apply a map to the humans cursor in order to add an index like so:
Template.showHumans.helpers({
humans: function() {
return Humans.find({}, {sort: {hotness: -1}}).map(function(human, index) {
human.rank = index;
return human;
});
}
});
<template name="showHumans">
<ul>
{{#each humans}}
<li>{{rank}}: {{name}}</li>
{{/each}}
</ul>
</template>
fetch() on the cursor, manipulating the sub-arrays, and then returning the whole array to the template? I don't know how else to do it since spacebars doesn't seem to support @index.Template.registerHelper('count1', function(count) { return count + 1; }); and then use it like so... {{count1 @index}} ...in your spacebars template.As taken from the spacebars documentation:
You can use a special variable @index in the body of #each to get the 0-based index of the currently rendered value in the sequence.
In Meteor 1.0.2.1, you can do the following:
{{#each humans}}
{{this}}
{{/each}}
This is because #each iterates through the array, making the this in each loop simply equal to the current value.
{{@index}}for arrays and{{@key}}for objects. On the other hand, I think a custom template helper or a global handlebars helper would be more extensible.