#each loop over multiple documents from a collecti

2019-09-24 10:22发布

I have a Meteor collection called Tasks

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

So something like this

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

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

How would I got about doing this in Meteor?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-24 10:59

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

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

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.

查看更多
登录 后发表回答