How can I get the index of an array in a Meteor template each loop?

meteor >= 1.2

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:

{{#each getArray}}
  <div class="item" data-value="{{@index}}">{{this}}</div>
{{/each}}

or, if you want to use the index inside a helper:

{{#each getArray}}
  <div class="item" data-value="{{someHelper @index}}">{{this}}</div>
{{/each}}

meteor < 1.2

Sometime in the future, spacebars may offer the ability to determine the index directly in the template. However, as of this writing, the only way to get the index is to modify the result returned by the helper. For example you could have getArray return an array of objects which contain a value and an index, like this:

getArray: function() {
  var self = this;
  self.myArray = self.myArray || [];
  return _.map(self.myArray, function(value, index){
    return {value: value, index: index};
  });
}

And the template could use the index like this:

<template name="someObject">
  {{#each getArray}}
    <div class="item" data-value="{{index}}">{{value}}</div>
  {{/each}}
</template>

Also see this answer for a similar example with cursors.

It’s worth mentioning that you probably don’t need to store the index in the DOM itself via data-value, unless it’s needed by an external plugin. As you can see in the example below, each item has a context with an index value. For more information, see this blog post.

Template.someObject.events({
  'click .item': function() {
    console.log(this.index);
  }
});

Leave a Comment