Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

arrays - #each loop over multiple documents from a collection in a single iteration

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...