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

给你一囗甜甜゛ 提交于 2019-12-21 04:32:14

问题


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?


回答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)




回答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;
    return document;
});



回答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 value is at this index number : {{index}}
{{/each}}


来源:https://stackoverflow.com/questions/22142432/print-the-loop-index-in-meteor-js-templates

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