Creating a numbered list for Meteor data

纵饮孤独 提交于 2019-12-20 04:32:50

问题


Is there a way to get "the number" for a numbered list of the items I have in a Meteor collection. I know I can do it in html, but I feel like it would be much easier to style if I could just drop something in the {{spacebars}}. If there's better terminology I could be using, please let me know. Something like this.

List of top 20 movies:

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

回答1:


I do not properly understand your question, neither do I know much about Meteor-Collections, but in general, if you iterate over an Array and want to get the index of each element, you could do it easily with:

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

 0:1
 1:2
 2:3

See MDN for forEach().




回答2:


There is pull request which does exactly what you want:

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

Until they merge it you can use other approach:

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




回答3:


Try it with using "map" from Underscore.js.

I'm expecting you have movies in your "Movie" collection and they look something like this:

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

... and so on ...

And here is "yourTemplate" helper function:

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;
    }
});

So now you can use it in your template like this:

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


来源:https://stackoverflow.com/questions/28626410/creating-a-numbered-list-for-meteor-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!