EmberJS - Defining Routes



The router matches the current URL with routes responsible for displaying template, loading data and setting up an application state. The router map() method is used for defining the URL mappings that pass a function which takes parameter as an object to create the routes. The {{ link-to }} helper navigates the router.

To define a route, use the following command in your project folder −

ember generate route route-name

It creates the route file app/routes/name_of_the_route.js, a template for the route at app/templates/name_of_the_route.hbs, and unit test file at tests/unit/routes/route_name_of_the_test.js.

You can define the URL mappings by using the map() method of router. This can be invoked with the this value to create an object for defining the route.

Router.map(function() {
   this.route('link-page', { path: '/path-to-link-page' });
   .
   .
   this.route('link-page', { path: '/path-to-link-page' });
});

The above code shows how to link the different pages by using the router map. It takes the linkpage name and path as an argument.

The below table shows different types of routes −

S.No. Routes & Description
1 Nested Routes

It specifies the nested routes by defining a template inside another template.

2 Dynamic Segments

It begins with a : in the route() method followed by an identifier.

3 Wildcard/Globbing Routes

Wildcard routes are used for matching the multiple URL segments.

Example

The following example shows how to define a route for displaying data. Open the .hbs file created under app/templates/. Here, we have created the file as routedemo.hbs with the following code −

<h2>My Books</h2>
<ul>
   <li>Java</li>
   <li>jQuery</li>
   <li>JavaScript</li>
</ul>

Open the router.js file to define URL mappings −

import Ember from 'ember';                    
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('routedemo');
});

export default Router;

Create the application.hbs file and add the following code −

//link-to is a handlebar helper used for creating links
{{#link-to 'routedemo'}}BookDetails{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages will 
appear inside this section

Output

Run the ember server and you will receive the following output −

Ember.js Defining Routes

When you click on the link of the output, a result as in the following screenshot will be generated −

Ember.js Defining Routes
emberjs_router.htm
Advertisements