How to get #each index from template instance?


#1

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:

<body>
  {{#each children}}
    {{> child }}
  {{/each}}
</body>

<template name="child">
  {{this}}
</template>
Template.body.helpers({
  children: [ 'A', 'B' ]
});

Template.child.onRendered(function(){
  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.


#2

Can you pass it down as a template parameter?
Something like this : http://meteorpad.com/pad/h2ijEuYSPHg6bdsj7/Child%20Template%20Index

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


#3

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


#4

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 : http://meteorpad.com/pad/sthXDRPYnMsTykBSF/Child%20Template%20Index%202 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
      }
      });

#5

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}}
{{/each}}

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.


#6

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


#7

This is pretty clever!


#8

This might help you.


#9

Is there a way to get @index from code?