Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the loop index in Meteor.js templates [duplicate]

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. That is, if the length of the objects list is 100 I want to print the numbers from 1 to 100 in the template. How can I do this?

like image 427
Sajid Ahmad Avatar asked Mar 03 '14 09:03

Sajid Ahmad


3 Answers

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)

like image 175
Tarang Avatar answered Sep 22 '22 15:09

Tarang


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

Template.yourtemplatename.objects = YourCollection.find().map(function(document, index){
    document.index = index;
    return document;
});
like image 42
waitingkuo Avatar answered Sep 23 '22 15:09

waitingkuo


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 value is at this index number : {{index}}
{{/each}}
like image 23
Guidouil Avatar answered Sep 24 '22 15:09

Guidouil