为Meteor数据创建编号列表

Creating a numbered list for Meteor data

本文关键字:编号 列表 创建 数据 Meteor      更新时间:2024-02-15

有没有办法为Meteor集合中的项目编号列表获取"编号"。我知道我可以在html中完成,但我觉得如果我可以在{{空格键}}中放入一些东西,那么样式会容易得多。如果有更好的术语我可以使用,请告诉我。像这样的东西。

前20部电影列表:

    {{#each movie}}
         Movie #{{number}} {{movie_name}} {{review_score}}
    {{/each}}

我不太理解你的问题,我对Meteor Collections也不太了解,但一般来说,如果你迭代一个数组并想获得每个元素的索引,你可以很容易地使用:

[1,2,3].forEach(function(e,i){ console.log(i+":"+e); })
 0:1
 1:2
 2:3

请参阅MDN以获取for Each()。

有一个拉取请求,它正是你想要的:

{{#each movie}}
   {{@index}}{{movie}}
{{/each}}

在他们合并之前,你可以使用其他方法:

如何在每次循环中获得Meteor模板中数组的索引?

尝试使用Undercore.js.中的"map"

我希望你的"电影"收藏中有电影,它们看起来像这样:

{
    title: "Shawshank Redemption",
    score: 92
},
{
    title: "Forrest Gump",
    score: 96
},
{
    title: "Green Mile",
    score: 91
},
{
    title: "The Godfather",
    score: 95
}

等等

这里是"yourTemplate"的辅助函数:

Template.yourTemplate.helpers({
    movie: function () {
        var loadMovies = Movie.find({}, {sort: {score: -1}, limit: 20}).fetch(); // added descending sorting by review score
        var array = _.map(loadMovies, function(movie, index) {
            return {
                    number: index+1, // incrementing by 1 so you won't get 0 at the start of the list
                    movie_name: movie.title,
                    review_score: movie.score
                   };
        });
        return array;
    }
});

所以现在你可以在你的模板中使用它,如下所示:

<template name="yourTemplate">
    {{#each movie}}
         Movie #{{number}} {{movie_name}} {{review_score}}
    {{/each}}
</template>