Skip to content Skip to sidebar Skip to footer

Print The Loop Index In Meteor.js Templates

I have a list of objects in meteorjs which I am iterating in meteorjs templates like {{#each objects}} {{/each}} In the template I want to print the number of the loop iteration.

Solution 1:

You can't do this at the moment without giving in an index in your helper, i.e

Template.yourtemplatename.object_with_index = function() {
    var objects = Template.yourtemplatename.objects();

    for(var i = 0; i=objects.length; i++) {
        objects[i].index = i;
    }

    return objects;
}

Then do:

{{#each object_with_index}}
    <p>This is number {{index}}</p>
{{/each}}

Not the prettiest way, but other variations would basically do the same thing under the hood (e.g if you used a map)

Solution 2:

If you objects is a cursor, you can use its map method:

Template.yourtemplatename.objects = YourCollection.find().map(function(document, index){
    document.index = index;
    returndocument;
});

Solution 3:

I made a global helper that add an index to an array :

UI.registerHelper('addIndex', function(thatArray) {
  if (thatArray && thatArray.length) {
    $.each(thatArray, function (position, thatObject) {
      thatObject.index = position;
      thatArray[position] = thatObject;
    });
    return thatArray;
  }
});

and then you call it like that :

{{#each addIndex arrayWithoutIndex}}
  The current valueis at this index number : {{index}}
{{/each}}

Post a Comment for "Print The Loop Index In Meteor.js Templates"