a blog for those who code

Monday, 18 July 2016

Getting started with Routing in Ember.js

In this post we will be discussing about getting started with Routing in Ember.js. In Ember, route is not going to be just a route (i.e. some URL) but it also going to be a collection of methods and actions. So in Ember, routes behaves as a route as well as a controller.


In Ember, routes determine what code is executed and which view is displayed. One thing to note that Ember has only one router i.e. all requests are sent to the router router.js which determines which route to call.

How to Create Ember Route

ember generate route name --pod

The above will create two files route.js and template.hbs inside name folder. The route.js file code is shown below :

import Ember from 'ember';

export default Ember.Route.extend({

The router.js will be updated with the following code :

import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType

Router.map(function() {

export default Router;


Ember also has a concept of Subroute which is nothing but a route inside a route or simply child route. If we need to create a subroute for our name route then we will run below command

ember generate route name/childname --pod

After this our router.js will be automatically updated with the new code as shown below, where its added a childname as a route to name.

Router.map(function() {
  this.route('name', function() {

Now you can see a childname folder inside name folder which also has route.js and template.hbs as shown below.

Dynamic Routes

A dynamic route is a portion of a URL that starts with a : and is followed by an identifier. Now to create a dynamic route you need to create a route with a parameter as shown below where id will become the name of the variable which will be going to the model to get that specific value.

this.route('childname', {path: ':id'});

Redirecting to New Route

If you need to send someone to a new route you can use transitionTo which reads the routes table and determines the appropriate URL. The code to route is shown below

this.transitionTo('name') // for route 
this.transitionTo('name.childname') //for subroute
this.transitionTo('name.childname', model) // for dynamic routes

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment