Search code examples
javascriptmeteoriron-router

Dynamic pathFor on Meteor/Iron Router


I'm new to Meteor and I'm trying to create a dynamic value for pathFor. For example, let's say I have the following routes:

  • brands.list: it lists all laptops brands (E.g. Apple, Acer, etc.);
  • brands.single: it lists all laptops from x brand (e.g. Macbook Pro, Macbook Air, etc.);
  • product.single: it displays the selected product.

I'd like to use the same list template to list all laptops brands and products:

{{#each lists}}
  <li><a href="{{pathFor route=listUrl}}">{{title}}</a></li>
{{/each}}

At first, I thought I could pass a listUrl value and set it to the right path inside the data context, like this:

this.layout('AppLayout', {
  data: {
    listUrl: 'product.single',
    lists: Products.find({brand: this.params.slug})
  }
});

This way, I could pass listUrl as brands.single in the brands.list route or as product.single in the brands.single one.

However, it doesn't work. Any ideas on how to solve this?


Solution

  • When you do {{#each lists}} the listUrl value is then trying to be found in context of each item of lists. So you can either put the listUrl variable inside each item in lists, or access parent context like this:

    {{#each lists}}
      <li><a href="{{pathFor route=../listUrl}}">{{title}}</a></li>
    {{/each}}