简体   繁体   中英

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 eg

 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

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>

You could extend your items in helper, like

items: function () {
    var counter = 0;
    return itemInCollection.find().map(function ( item ) { 
        return {
            name: item.name,
            counter: counter++
        };
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM