在Meteor中使用#each,检查是否'最后'已到达集合中的元素

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

本文关键字:集合 元素 最后 Meteor #each 检查 是否      更新时间:2023-09-26

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

有什么方法可以在Meteor中检查这种情况吗?

如果你们中有人想知道如何使用集合游标进行同样的操作,那么多亏了handlebal-helpers包,有一种更简单的方法。

然后你可以使用:

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

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

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

PS:这也适用于阵列

使用undercore.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.PparentData()是什么时候在流星中引入的)。

Metroet(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
            }
        })
    }
})

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