在Meteor中使用#each,检查集合中是否有"last"元素

Ger*_*rbó 8 javascript meteor spacebars meteor-blaze

我正在使用{{#each}}在Meteor中迭代一个集合,我想知道我是否在最后一个元素中,就像我在AngularJS中使用ngRepeat和$ last一样.

例如,它可用于构建人类可读的枚举,如"我喜欢猫,狗和海豚":

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>
Run Code Online (Sandbox Code Playgroud)

有没有办法检查Meteor中的这种情况?

Ron*_*nen 7

如果你们中的任何一个人想知道如何对集合游标做同样的事情,那么由于车把助手包,有一个更简单的方法.

然后你可以使用:

$ mapped - 将$ first,$ last和$ index映射到游标或数组

结合模板中的$ last helper,如下所示:

{{#each $mapped myCursor}}
  {{name}}{{#unless $last}},{{/unless}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

PS:这也适用于数组


小智 6

使用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>
Run Code Online (Sandbox Code Playgroud)

使用流星1.1.0.1为我工作的反应数据源(我不知道什么时候在流星中引入了Template.parentData()).


Pep*_*L-G 1

流星(版本 1.0)尚不支持此功能,但您可以通过执行以下操作自己添加它:

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
            }
        })
    }
})
Run Code Online (Sandbox Code Playgroud)

然而,这对于反应性来说并不能很好地发挥作用(使其在反应性下正常工作要困难得多,我想这就是为什么这还不是内置功能的原因),但是如果您返回一个不依赖于任何反应式数据源,这应该可以正常工作。