有没有办法在迭代Meteor中的集合时获取索引?

use*_*594 6 handlebars.js meteor

下面的示例将生成播放器名称列表,其中播放器是MongoDB数据库中的数据集.

<template name="players">
  {{#each topScorers}}
    <div>{{name}}</div>
  {{/each}}
</template>
Run Code Online (Sandbox Code Playgroud)

但是,我想连续显示其中的四个,并且在打印了四个玩家之后,我想将线分开<hr />,然后继续.例如,

<template name="players">
  {{#each topScorers}}
    <div style="float:left;">{{name}}</div>
    {{if index%4==0}}
      <hr style="clear:both;" />
    {{/if}
  {{/each}}
</template>
Run Code Online (Sandbox Code Playgroud)

在迭代集合时如何做这样的事情?

小智 7

与保持集合的反应性一致的另一种解决方案是使用具有映射光标功能的模板助手.

这是一个示例,说明如何在将每个索引与集合一起使用时返回索引:

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;
};
Run Code Online (Sandbox Code Playgroud)


Tom*_*man 6

现在没有简单的方法可以做到这一点,最新版本的把手支持一个@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;
});
Run Code Online (Sandbox Code Playgroud)

这样做的缺点是你失去了流星{{#each}}助手的优点,当单个项目发生变化时,助手不会反复重新渲染整个列表.

编辑:感谢@zorlak指向https://github.com/meteor/meteor/issues/281#issuecomment-13162687