在Meteor中遍历集合时是否有一种方式可以获取索引?

6
下面的示例将生成一个球员名称列表,其中球员是来自MongoDB数据库的数据集。
<template name="players">
  {{#each topScorers}}
    <div>{{name}}</div>
  {{/each}}
</template>

然而,我希望一行显示四个玩家,在打印出四个玩家后,我想用<hr />来分割这一行,然后继续显示。例如:
<template name="players">
  {{#each topScorers}}
    <div style="float:left;">{{name}}</div>
    {{if index%4==0}}
      <hr style="clear:both;" />
    {{/if}
  {{/each}}
</template>

我如何在迭代集合时执行类似的操作?
2个回答

7

另一种与维护集合的反应性相一致的解决方案是使用带有map cursor function的模板助手。

以下是一个示例,展示了在使用each与集合时如何返回索引:

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

6

目前没有简单的方法来实现这一点,最新版本的handlebars支持一个@index字段(可以做到你想要的效果),但它还没有在meteor的版本中实现 - https://github.com/meteor/meteor/issues/489

当然,你可以实现自己的{{#each_with_index}}助手函数,它看起来会像这样:

Handlebars.registerHelper('each_with_index', function(items, options) {
  var out = '';
  for(var i=0, l=items.length; i<l; i++) {
    var key = 'Branch-' + i;
    out = out + Spark.labelBranch(key,function(){ 
      options.fn({data: items[i], index: i});
    });
  }

  return out;
});

这样做的缺点是,您会失去Meteor的{{#each}}助手的优点,当单个项目更改时,它不会反应性地重新呈现整个列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接