iron:router

October 21, 2015

iron:router is probably one of the most essential package every meteor apps should have. What is it for? Well, routing of course. See the code below to see what I mean.

Router.map(function () {
    this.route('about');
}

This code tells meteor to serve the about view template when the browser request for http://localhost:4000/about page. It is actually a shortcut to write the following as the path and template are the same name as the route.

Router.map(function () {
    this.route('about',{
        path: '/about',
        template: 'about'
    });
}

One important route to define is the home route which will serve the home page when user land on your side. Note that I omitted the template name since it is the same as the route name.

Router.map(function () {
    this.route('home',{
        path: '/'
    });
}

One can configure the default layout template to use. Also for loading and 404 templates.

Router.configure({
  layoutTemplate : 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound'
});

The following shows how you can customise the url to include the plan id for individual plan.

Router.route("plan_show", {
  route : "/plan/:_id",
  data : function(){
    return Plans.findOne({_id : this.params._id});
  }
});

pathFor command is useful for getting the path in view template. Therefore, one should only change the actual path in the router.js file and use pathFor in view templates to minimise routing mistakes. Other command include urlFor and linkTo.

{{pathFor 'about' }}         '/about'
{{pathFor 'plan_show' _id }} '/plan/_id'

Other useful hooks are but we wouldn’t go into detail now. Take a look at their documentation for more.

Router.onBeforeAction
Router.onAfterAction
Router.onRun
Router.onReRun
Router.onStop