In meteor is there a way to access array index in spacebars [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:17:01

问题:

This question already has an answer here:

I am using meteor Shark branch.

Is there a way to access array index inside each block helper in spacebars?

I am looking for something like this.

{{#each humans}}   {{this.arrayIndex}} {{/each}} 

回答1:

meteor >= 1.2

Spacebars gained a lot of functionality in 1.2, including a native @index. Helpers are no longer needed to solve this problem - you can simply do this:

meteor

I saw a similar example using template helpers in the meteor book in the "animations" chapter. You can apply a map to the humans cursor in order to add an index like so:

Template.showHumans.helpers({   humans: function() {     return Humans.find({}, {sort: {hotness: -1}}).map(function(human, index) {       human.rank = index;       return human;     });   } }); 


回答2:

As taken from the spacebars documentation:

You can use a special variable @index in the body of #each to get the 0-based index of the currently rendered value in the sequence.



回答3:

In Meteor 1.0.2.1, you can do the following:

{{#each humans}}   {{this}} {{/each}} 

This is because #each iterates through the array, making the this in each loop simply equal to the current value.



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