Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get index while iterating through a collection in Meteor? [duplicate]

The below example will generate a list of names of players, where players is a data set from a MongoDB database.

<template name="players">
  {{#each topScorers}}
    <div>{{name}}</div>
  {{/each}}
</template>

However, I want to display four of them in a row, and after four players is printed, I want to divide the line by <hr /> and then continue. For instance,

<template name="players">
  {{#each topScorers}}
    <div style="float:left;">{{name}}</div>
    {{if index%4==0}}
      <hr style="clear:both;" />
    {{/if}
  {{/each}}
</template>

How can I do something like that while iterating through collections?

like image 339
user482594 Avatar asked Nov 11 '12 09:11

user482594


1 Answers

Another solution, in line with maintaining the reactivity of the collection, is to use a template helper with the map cursor function.

Here's an example showing how to return the index when using each with a collection:

index.html:

<template name="print_collection_indices">
  {{#each items}}
    index: {{ this.index }}
  {{/each}}
</template>

index.js:

Items = new Meteor.Collection('items');

Template.print_collection_indices.items = function() {
  var items = Items.find().map(function(doc, index, cursor) {
    var i = _.extend(doc, {index: index});
    return i;
  });
  return items;
};
like image 77
davidd8 Avatar answered Nov 15 '22 10:11

davidd8