How to use URL parameters using Meteorjs

kstieger picture kstieger · Mar 1, 2014 · Viewed 8.5k times · Source

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.

Answer

Dsyko picture Dsyko · Mar 2, 2014

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.