8

How can I use URL parameters with meteor.

The URL could look like this: http://my-meteor.example.com:3000?task_name=abcd1234

I want to use the 'task_name' (abcd1234) in the mongodb query in the meteor app.

eg.

Template.task_app.tasks = function () {
  return Tasks.find({task_name: task_name}); 
};

Thanks.

kstieger
  • 133
  • 1
  • 5

1 Answers1

20

You are probably going to want to use a router to take care of paths and rendering certain templates for different paths. The iron-router package is the best one available for that. If you aren't using it already I would highly recommend it.

Once you are using iron-router, getting the query strings and url parameters is made very simple. You can see the section of the documentation here: https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#route-parameters

For the example you gave the route would look something like this:

Router.map(function () {
  this.route('home', {
    path: '/',
    template: 'task_app'
    data: function () {
      // the data function is an example where this.params is available

      // we can access params using this.params
      // see the below paths that would match this route
      var params = this.params;

      // we can access query string params using this.params.query
      var queryStringParams = this.params.query;

      // query params are added to the 'query' object on this.params.
      // given a browser path of: '/?task_name=abcd1234
      // this.params.query.task_name => 'abcd1234'
      return Tasks.findOne({task_name: this.params.query.task_name});

    }
  });
});

This would create a route which would render the 'task_app' template with a data context of the first task which matches the task name.

You can also access the url parameters and other route information from template helpers or other functions using Router.current() to get the current route. So for example in a helper you might use Router.current().params.query.task_name to get the current task name. Router.current() is a reactive elements so if it is used within the reactive computation the computation will re-run when any changes are made to the route.

Dsyko
  • 1,499
  • 14
  • 27
  • 1
    Now how to access that param inside the event of the template being loaded in your example. base in your example, how to access this.params.taskname in Template.home.events({}) – JCm Apr 18 '15 at 10:25
  • This answer only tells us how to access the query params in the router.js file. It doesn't explain how to access the query params in a Template function, as the original example states. – JoeTidee May 04 '15 at 23:14
  • 3
    You can use Router.current().params anywhere within Meteor if you are using Iron Router. It is a reactive variable so be aware that if you use it within a reactive computation the function will be re-run whenever the parameters change. – Dsyko May 08 '15 at 16:43