8

我正在使用 {{#each}} 遍历 Meteor 中的集合,我想知道我是否在最后一个元素中,就像我在 AngularJS 中使用 $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>

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

4

3 回答 3

8

如果你们中的任何人想知道如何对集合游标做同样的事情,多亏了handlebar-helpers包,有一个更简单的方法。

然后你可以使用:

$mapped - 将 $first、$last 和 $index 映射到光标或数组

与模板中的 $last 助手相结合,如下所示:

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

PS:这也适用于数组

于 2015-07-27T22:47:49.177 回答
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>

为我使用流星 1.1.0.1 的反应数据源(我不知道 Template.parentData() 何时在流星中引入)。

于 2015-04-13T15:40:54.327 回答
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
            }
        })
    }
})

但是,这对反应性不好(使其与反应性正常工作要困难得多,我想这就是为什么这还不是内置功能的原因),但是如果您返回一个不依赖于任何的简单数组反应数据源,这应该可以正常工作。

于 2014-11-20T09:55:26.773 回答