在Meteor中对嵌套{{#each}}进行排序?

时间:2016-01-27 14:16:55

标签: meteor each meteor-blaze spacebars

在流星指南中我找到了下面的代码,我想知道todo.tags是否可能以某种方式排序,可能是通过帮助方法?

{{#each todo in todos}}
  {{#each tag in todo.tags}}
    <!-- in here, both todo and tag are in scope -->
  {{/each}}
{{/each}}

1 个答案:

答案 0 :(得分:0)

一个选项是创建一个单独的模板助手,对您tags数组中的所有元素进行排序。要按升序对元素进行排序,您可以使用 _.sortBy(list, iteratee, [context]) ,例如:

if (Meteor.isClient) {
  Template.todos.helpers({
    todos: function() {
      return Todos.find();
    },
    sortedTags: function(todo) {
      return _.sortBy(todo.tags, function(tag) {
        return tag;
      });
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function() {
    if (Todos.find().count() === 0) {
      Todos.insert({
        name: "homework",
        tags: ["school", "college", "university"]
      });
    }
  });
}
<template name="todos">
  {{#each todo in todos}}
    {{todo.name}}
    <ul>
      {{#each tag in sortedTags todo}}
        <li>{{tag}}</li>
      {{/each}}
    </ul>
  {{/each}}
</template>

这也可以通过评论中提供的示例数据结构实现:

{
   "gtext":"Money",
   "owner":"qDqGDaXjaHXNhX95u",
   "username":"prsz",
   "order":0,
   "tasks":[
      {
         "taskName":"Test subtask1",
         "taskOrder":3
      },
      {
         "taskName":"Test subtask2",
         "taskOrder":1
      }
   ]
}
<template name="goals">
  {{#each goal in goals}}
    {{goal.gtext}}
    <ul>
      {{#each task in sortedTasks goal}}
        <li>{{task.taskName}}</li>
      {{/each}}
    </ul>
  {{/each}}
</template>
if (Meteor.isClient) {
  Template.goals.helpers({
    goals: function() {
      return Goals.find();
    },
    sortedTasks: function(goal) {
      return _.sortBy(goal.tasks, function(task) {
        return task.taskOrder;
      });
    }
  });
}

这是MeteorPad