Skip to content

Meteor.Router v3 API

tmeasday edited this page Mar 24, 2013 · 1 revision

Meteor Router API v3

Based on ideas from various sources, particularly Chris Mather's mini-pages.

Meteor.Router.add()

  • General syntax:
Meteor.Router.add('/path/to/route', routeProperties);

routeProperties can contain any of:

  • to - a string indicating the template to be render, or a function (see below).
    • if this string starts with a '/', it's assumed to be a URI and a 'redirection' happens.
    • this is the only property REQUIRED.
  • as - the name of the route. Defaults to to.
  • with - the data context to be set for the template. Can be a reactive function returning a context.
  • and - a function to run along with the route. Use it for side-effects (NOTE: it's best to put such things in filters).

If to is a function, it can return either:

  • a string, indicating a template name, or if starting with '/', a route to redirect to.
  • an object, which
    • MUST have a to property -- the name of the template.
    • can also have a with property -- the data context.

If to is a function, the route is un-named unless as is set.

If more than one route has the same name, the first such route is used as the named route.

Meteor.Router.add('/foo', function() { return 'foo' });

is equivalent to

Meteor.Router.add('/foo', {to: function() { return 'foo' }});
Meteor.Router.add('/foo', 'foo');

is equivalent to

Meteor.Router.add('/foo', {to: 'foo'});

Named routes

A named route creates convenience helpers for your use. Suppose we have a route named 'home':

Meteor.Router.add('/', 'home');

Then the following are made available:

  • Meteor.Router.homePath() - returns '/'

  • Meteor.Router.homeUrl() - returns 'http://example.com/'

  • {{homePath}} and {{homeUrl}} are similar.

  • Meteor.Router.to.home() is a shortcut for Meteor.Router.to(Meteor.Router.homePath())

If the route has named parameters, then an object with those named properties should be passed in:

Meteor.Router.add('/posts/:_id', {to: 'post', with: function(id) { return Posts.findOne(id); }});

Meteor.Router.postPath({_id: 'abcd'}); // -> 'posts/abcd'

Filters

Filters continue to operate on template names. The pageJS context is augmented with a with property indicating the result of the with function, where appropriate.

Like a to function, a filter can return either:

  • a string, indicating a template name, or a route to redirect to (this stops further processing).
  • an object with a to property and optionally a with property.
  • null, indicating to not alter the current to and with.