In Meteor using #each, check to see if the item has reached the "last" in the collection

I iterate through a collection in Meteor using {{#each}} and I would like to know if I am in the last element, how can I do this in AngularJS when using ngRepeat with $ last.

It can be used, for example, to create human-readable listings like "I like cats, dogs and dolphins":

Template.myTemplate.helpers({ likedAnimals: function(){return ['dogs','cats','dolphins'];} }); <template name='myTemplate'> I like {{#each likedAnimals}} {{#if !$first && !$last}}, {{/if}} {{#if $last}} and {{/if}} {{this}} {{/each}} </template> 

Is there a way to test this condition in Meteor?

+8
javascript meteor spacebars meteor-blaze
source share
3 answers

Using underscore.js :

 Template.registerHelper('last', function(list, elem) { return _.last(list) === elem; } ); <template name='myTemplate'> {{#each likedAnimals}} {{#if last ../likedAnimals this}} I'm the last ! {{/if}} {{/each}} </template> 

Worked with a reactive data source for me with meteor 1.1.0.1 (I do not know when Template.parentData () was introduced into the meteor).

+6
source share

If any of you are wondering how to do the same with collection cursors, it’s much easier with the help of the handlebar-helpers package .

Then you can use:

$ mapped - maps $ first, $ last and $ index to your cursor or array

combined with the $ last helper in your template:

 {{#each $mapped myCursor}} {{name}}{{#unless $last}},{{/unless}} {{/each}} 

PS: this also works with arrays

+6
source share

This is not yet supported in meteor (version 1.0), but you can add it yourself by doing something like this:

 Template.myTemplate.helpers({ likedAnimals: function(){ var animals = ['dogs','cats','dolphins'] return animals.map(function(animal, index){ return { name: animal, isFirst: index==0, isLast: index==animals.length-1 } }) } }) 

However, this does not reflect well on reactivity (which makes its work with reactivity much more difficult, and I think this is the reason why this is not a built-in function yet), but if you return a simple array that does not depend on any source of reactive data, this should work fine.

+1
source share

All Articles