Search code examples
javascriptmeteoriron-router

Meteor. Passing an argument to a helper to populate a page based on the argument


I'm trying to populate a meteor template based on a parameter I send in through the address bar.

I'm using Iron router and when I looked in its documentation I found this example

Router.route('/post/:_id', function () {
  this.render('Post', {
    data: function () {
      return Posts.findOne({_id: this.params._id});
    }
  });
});

I tried something similar but I'm struggling to find how I actually use that data property in the template. Previously I've used a template helper to do a find on the db which has worked perfectly as long as its always the same find command. Now that I want to customise that find based on what I pass in through the address bar I'm struggling to do that.

Using the Iron router example above I tried something like this

Router.route('fruit/:_colour', function () {
  this.render('fruitTemplate', {
    data: function () {
      return FruidDb.find({colour: this.params._colour});
    }
  });
});

This is where I get stuck. Normally to populate my template I would use a helper like below

Template.fruitTemplate.helpers({
  fruitByColour: function() {
      return FruidDb.find({colour: "green");
  }
});

then just foreach through each fruitByColour

But now that I'm "dynamically" getting that data I'm not sure how to get the data that is returned from the Route to the helper.

Maybe I'm doing this completely wrong. If there is a better way to just pass the param to the helper and do the db.find from there that would probably be best but I'm finding it hard to see the best way to do this and would greatly appreciate any help


Solution

  • I found the answer thanks to some code I found on this question Meteor Iron Router : Passing data between routes

    Basically I don't need to define a separate helper I can just pass the same data as I had in the helper just like this.

    Router.route('fruit/:_colour', function () {
      this.render('fruitTemplate', {
        data: {
          fruitByColour: function () {
            return FruitDb.find({colour: this.params._colour});
          }
        }
      });
    });