在单次迭代#each遍历多个文档从集合 [英] #each loop over multiple documents from a collection in a single iteration

查看:154
本文介绍了在单次迭代#each遍历多个文档从集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流星集名为任务

我想对每2缠一个div模板显示出来。

I would like to display them on the template with a div wrapped around every 2.

因此​​,像这样

<div>
  {{task 1}}
  {{ task 2 }}
</div>

<div>
  {{task 3}}
  {{ task 4 }}
</div>

如何将我关于流星这样做呢?

How would I got about doing this in Meteor?

推荐答案

要遍历有什么用一个助手来定义 - 在这种情况下,你可以不喜欢返回一个对象数组包含第一和第二你要任务,以显示:

Use a helper to define what you want to iterate over -- in this case, you could do something like return an array of objects that contain the first and second tasks you want to display:

<template name='whatever'>
  {{#each getTasksToIterate}}
    <div>
      {{> task firstTask}}
      {{> task secondTask}}
    </div>
  {{/each}}

然后,在你的助手,定义函数 getTasksToIterate

Then, in your helpers, define the function getTasksToIterate:

Template.whatever.helpers({
  getTasksToIterate: function() { 
    var tasks = [];
    _.each(this.tasks, function(task, index) { 
      if (index % 2 === 0) { // Pick the odd ones
        tasks.push({firstTask: elem, secondTask: this.tasks[index + 1]}); 
      }

    return tasks;
  }
});

请注意,这里假设你有一个甚至多个任务;如果你偶尔有奇数你需要适当的if语句等处理的

Note that this assumes you have an even number of tasks; if you occasionally have an odd number you'd need to deal with that with appropriate if statements, etc.

这篇关于在单次迭代#each遍历多个文档从集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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