How to get #each index from template instance?


If I have a template instance that’s inside and #each, how can I get the current index? I say current because of course it can change as the context changes. For example:

  {{#each children}}
    {{> child }}

<template name="child">
  children: [ 'A', 'B' ]

  var templateInstance = this;
  // Get current child index

Just to be clear I need to get the index out of the template instance because that’s all I have. I don’t have access to the collection used by the #each or the helper method.


Can you pass it down as a template parameter?
Something like this :

{{#each children}}
{{> child child=this index=@index}}


Nope. I don’t have control of the #each.


well, that’s much more difficult… :grin: Only thing I can think of is iterate over the list of parent’s children and compare to self : Which I think is pretty inefficient, and I’m not sure exactly how the dom equality works ( like what if the elements are empty divs and have nothing unique in them), but the indexes are changing at least in the meteorpad example.

Inside the child :

    var siblings = Template.instance().firstNode.parentElement.children;
    _.each( siblings, function(sibling, index){
      if( sibling===Template.instance().firstNode ){
          // this is child template index


It seems to me that there could be something easier. Checkout this MeteorPad

Hopefully it is what you are looking for.

{{#each players}}
  {{> player player=this propCounter=propPlayersCounter}}

propPlayersCounter: function() {
  return Template.instance().myPlayersCounter++;

You see, that this counter is in correct order from the collection - just disable the sort once to see the changes.


I’ll have to go with looshi’s method for now since I don’t have control over the loop.


This is pretty clever!


This might help you.


Is there a way to get @index from code?