【问题标题】:Creating a numbered list for Meteor data为 Meteor 数据创建编号列表
【发布时间】:2015-04-21 23:31:39
【问题描述】:

有没有办法为我在 Meteor 集合中拥有的项目的编号列表获取“编号”。我知道我可以在 html 中做到这一点,但我觉得如果我可以在 {{spacebars}} 中放置一些东西,它会更容易设置样式。如果我可以使用更好的术语,请告诉我。像这样。

前 20 部电影列表:

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

【问题讨论】:

  • 如果您发布您尝试过的代码的 sn-p 或我们可以使用的东西,这将有所帮助。
  • 好的,我添加了一些东西。我在哪里有“数字”这个词,有没有办法在那里获得列表编号?

标签: javascript mongodb meteor


【解决方案1】:

我没有正确理解你的问题,我也不太了解 Meteor-Collections,但一般来说,如果你遍历一个数组并想要获取每个元素的索引,你可以轻松做到:

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

 0:1
 1:2
 2:3

请参阅 MDN 以获取 forEach()

【讨论】:

  • 我什至不知道我在寻找“索引”这个词。显然,某些版本的把手可以让您简单地使用 {{@index}},但不能使用 Meteor 的版本。我将尝试使用您在此处提供的内容和 Stack 上的其他解决方案,看看我想出了什么。
【解决方案2】:

pull request 正是您想要的:

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

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

How can I get the index of an array in a Meteor template each loop?

【讨论】:

  • 谢谢,这正是我想要发现的。这也是表达问题的正确方法,Thomas Junk 向我介绍了这一点(我可能只是等待它得到实施)。
【解决方案3】:

尝试使用来自Underscore.js 的“地图”。

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

{
    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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2013-06-09
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多