【问题标题】:Is there a way to get index while iterating through a collection in Meteor? [duplicate]有没有办法在迭代 Meteor 中的集合时获取索引? [复制]
【发布时间】:2012-10-31 01:28:08
【问题描述】:

以下示例将生成玩家姓名列表,其中玩家是来自MongoDB 数据库的数据集。

<template name="players">
  {{#each topScorers}}
    <div>{{name}}</div>
  {{/each}}
</template>

但是,我想连续显示其中四个,打印四个玩家后,我想将行除以&lt;hr /&gt;,然后继续。例如,

<template name="players">
  {{#each topScorers}}
    <div style="float:left;">{{name}}</div>
    {{if index%4==0}}
      <hr style="clear:both;" />
    {{/if}
  {{/each}}
</template>

如何在遍历集合时做类似的事情?

【问题讨论】:

    标签: meteor handlebars.js


    【解决方案1】:

    为了保持集合的反应性,另一种解决方案是使用带有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;
    };
    

    【讨论】:

      【解决方案2】:

      目前没有简单的方法可以做到这一点,最新版本的车把支持@index 字段(可以满足您的要求),但它尚未在流星版本中实现 - 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;
      });
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-18
        • 2020-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-27
        • 2019-12-12
        相关资源
        最近更新 更多