有没有办法在迭代 Meteor 中的集合时获取索引? [英] Is there a way to get index while iterating through a collection in Meteor?

查看:20
本文介绍了有没有办法在迭代 Meteor 中的集合时获取索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The below example will generate a list of names of players, where players is a data set from a MongoDB database.

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

但是,我想连续显示四个,打印四个玩家后,我想用<hr/>分割一行,然后继续.例如,

However, I want to display four of them in a row, and after four players is printed, I want to divide the line by <hr /> and then continue. For instance,

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

在迭代集合时如何做类似的事情?

How can I do something like that while iterating through collections?

推荐答案

另一种符合保持集合反应性的解决方案是使用带有 地图光标功能.

Another solution, in line with maintaining the reactivity of the collection, is to use a template helper with the map cursor function.

下面的例子展示了如何在将 each 用于集合时返回索引:

Here's an example showing how to return the index when using each with a collection:

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

这篇关于有没有办法在迭代 Meteor 中的集合时获取索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆