如何使用 Meteor Template Helper 增加和显示变量计数器?

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

我有一个 itemInCollection = new Meteor.Collection('stuff') 集合,我使用 itemInCollection.find() 获取其中的所有项目。现在我迭代生成的光标以在模板中显示 name 属性。

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

现在我只想在名字前面表示一个数字,例如

 1. John
 2. Doe
 3. Darling

如何在辅助函数中实现计数器?我尝试了以下方法:

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

我在模板中这样写:

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

但这给了我这样的感觉:

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

您可以在助手中扩展您的项目,例如

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

以下是您可以如何做到这一点:

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>