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

梦想与她 提交于 2019-12-03 13:36:56

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)

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;
});
Guidouil

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}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!