2
votes

In meteors guide i found the code below and I was wondering if todo.tags could be sorted somehow, maybe by a helpers method?

{{#each todo in todos}}
  {{#each tag in todo.tags}}
    <!-- in here, both todo and tag are in scope -->
  {{/each}}
{{/each}}
1
Can you post the javascript helpers code too? - Brett McLain
There is no helpers code. I found this code in the Meteor guide here: guide.meteor.com/blaze.html Normally, the todo.tags would appear in a natural order (in the order the were put into the collection/document) but I would like to sort them. - Peter
change todo.tags to this.tags - Ethaan
In which order do you want to sort them? - Matthias A. Eckhart
Ascending order by name. - Peter

1 Answers

0
votes

One option would be to create a separate template helper which sorts all elements in your tags array. To sort the elements in an ascending order, you could use _.sortBy(list, iteratee, [context]), for example:

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>

This can also be implemented with your sample data structure, provided in the comments:

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

Here's a MeteorPad.