Access Collection Index in Handlebars / Blaze #each loop

I was messing around with the Meteor Leaderboard example. Say I wanted to display the index of an element inside a #each handlebars loop:

{{#each players}}
  {{> player}}
{{/each}}

<template name="player">
  <div class="player {{selected}}">
    <span class="index">{{index}}</span>
    <span class="name">{{name}}</span>
    <span class="score">{{score}}</span>
  </div>
</template>

Usually you need to write a helper for this, but it's hard for me to figure out how to make it work with the Meteor collection.

How to do it? Thank.

+3
source share
4 answers

Blaze now has an @index function:

{{#each players}}
  {{> player index=@index}}
{{/each}}

<template name="player">
  <div class="player {{selected}}">
    <span class="index">{{index}}</span>
    <span class="name">{{name}}</span>
    <span class="score">{{score}}</span>
  </div>
</template>

Template.player.helpers({
  index() {
    var data = Template.currentData();
    if( data ) {
      return data.index;
    }
  }
});
+2
source

If you are just trying to show mongo generated id just use _id

 <span class="id">{{_id}}</span>

It will display the unique index identifier in the collection. It will not be so.

Perhaps I misunderstood your question. Sorry if I did.

0
source

. .

Template.player.data = function(data){

if(type){

return Template[ 'player' ](data);

}

}

{{#each players}}

{{data this}}

{{/each}}

.

0
source

This is how I solved it - not an ideal solution - using the fact that Mongo usually creates indexes that add value.

Template.item.index = function() {
    return Items.find().count() - Items.find({_id: {$lte: this._id}}).count() + 1
}

Then I use this in the template as follows: {{Index}}

Hope this helps!

0
source

All Articles