【问题标题】:How Do I Increment and Display Variable Counter Using Meteor Template Helper?如何使用 Meteor Template Helper 增加和显示变量计数器?
【发布时间】:2015-11-02 13:38:39
【问题描述】:

我有一个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

counter如何在helper函数中实现?我尝试了以下方法:

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

【问题讨论】:

    标签: javascript meteor spacebars meteor-helper


    【解决方案1】:

    您可以这样做:

    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>
    

    【讨论】:

      【解决方案2】:

      你可以在助手中扩展你的项目,比如

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-10
        相关资源
        最近更新 更多