Search code examples
javascriptmeteorspacebarsmeteor-helper

How Do I Increment and Display Variable Counter Using Meteor Template Helper?


I got a itemInCollection = new Meteor.Collection('stuff') collection and I use itemInCollection.find() to get all the items in it. Now I iterate over the resulting cursor to show the name attribute in the template.

<head>
  <title>hello</title>
</head>
<body>
  <h1>Welcome to Meteor!</h1>
  {{> hello}}
</body>

<template name="hello">
  <button>Click Me</button>
  {{#each item}}
     {{counter}} : {{name}}
  {{/each}}
</template>

Now I just want to represent a number in front of the name, like e.g.

 1. John
 2. Doe
 3. Darling

How can the counter be realized in the helper function? I tried the following:

Template.hello.helpers({
  'item': function() {
    return itemInCollection.find();
  },
 'counter': function() {
   var counter = PrimerList.find().count(),
      arr = [];
    for (var i = 0; i < counter; i++) {
      arr.push( i + 1 );
    }
    return arr;
  }
});

and in the template i wrote this:

  {{#each item}}
      {{#each counter}} {{this}} {{/each}} : {{name}}
  {{/each}}

but that gave me like:

1 2 3 John
1 2 3 Doe
1 2 3 Darling

Solution

  • Here is how you can do that:

    Template.hello.helpers({
        'item': function() {
            return itemInCollection.find().map(function(document, index) {
                document.index = index + 1;
                return document;
            });
        }
    });
    

    <template name="hello">
      <button>Click Me</button>
      {{#each item}}
         {{index}} : {{name}}
      {{/each}}
    </template>