Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Meteor using #each, check if 'last' element in the collection reached

I'm iterating through a collection in Meteor using {{#each}} and I would like to know if I'm in the last element, as I can do in AngularJS while using ngRepeat with $last.

It could be used, for example to construct human readable enumerations 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 any way to check this condition in Meteor?

like image 756
Gerard Carbó Avatar asked Nov 11 '14 10:11

Gerard Carbó


2 Answers

If any of you are wondering how to do the same with collection cursors, there's a much simpler way thanks to handlebar-helpers package.

You could then use:

$mapped - will map $first, $last, and $index onto your cursor or array

combined with $last helper in your template like that:

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

PS: this also works with arrays

like image 175
Ronen Avatar answered Oct 17 '22 11:10

Ronen


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 don't know when Template.parentData() was introduced in meteor).

like image 6
bidubida Avatar answered Oct 17 '22 12:10

bidubida