Multi level list with links in Meteor
Asked Answered
L

1

9

I have a collection with fields groupNumber and number:

groupNumber, number
=================
1, 1
1, 2
1, 3
1, 4
2, 1
2, 2
2, 3
2, 8
3, 4
3, 5
...

I can print the entire collection with

{{#each numbers}}
  <tr>
    <td>{{groupNumber}}</td>
    <td>{{number}}</td>
  </tr>
{{/each}}

but I need it to be links instead. So at the first page I need to see a list of the group numbers (1, 2, 3, ...) and when I've clicked one of the groups, I see the numbers belonging to this group.

I could easily achieve this if I had groupNumber and number split in two different collections and use iron-router to navigate between list of groups and list of numbers belonging to group. But how can I get this with the two fields in the same collection?

Lenhart answered 2/7, 2015 at 18:56 Comment(0)
S
5

Why don't you "group" your groups manually?

At first get all your group numbers.

var allValues = YourCollection.find().fetch();
var uniqueGroups = _.union(_.pluck(allValues, 'groupNumber')) //outputs [1,2,3]

After that, simple route will do the job:

Router.route('/group/:groupNumber?', function () {
  this.render('your_template', {
    data: function () {
      if(this.params.hasOwnProperty('groupNumber')){
          return {
             groupNumber: this.params.groupNumber
          }
      } else {
          var allValues = YourCollection.find().fetch();
          var uniqueGroups = _.union(_.pluck(allValues, 'groupNumber'))
          return {
              groups: uniqueGroups
          }
      }  
    }
  });
});

Then in your_template check, if you have groupNumber, show all numbers by YourCollection.find({groupNumber: this.groupNumber})

if not, then just render this.groups:

{{#each groups}}
<a href="/group/{{this}}">{{this}}</a>
{{/each}}
Staciestack answered 5/7, 2015 at 9:54 Comment(3)
What if I have two more levels group1, group2, group3, and group4?Lenhart
You're really asking a UX paradigm instead of using routes.Steinbok
The same logic applies with > 1 level of nesting or even recursive nesting. The only thing that seems missing from @Zuzel's answer is sorting which you presumably want to do at each level.Pontificate

© 2022 - 2024 — McMap. All rights reserved.