EmberJS – Router Nested Routes

You can define nested routes by defining a template inside another template by passing a callback to the current route.

Syntax

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

To create a nested route, run the below command −

ember generate route route_name/another_route_name

Example

The below example shows how to define nested routes for displaying one template inside another template. Open the file .hbs file created under app/templates/nestedroute. Here, we have created the file as fruits.hbs with the below code −

<h2>Fruits Page</h2>
<ul>
   <li>Orange</li>
   <li>Apple</li>
   <li>Banana</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('nestedroute', function() {
      this.route('fruits');
   });
});

//It specifies Router variable available to other parts of the app
export default Router;

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

{{#link-to 'nestedroute.fruits'}}fruits{{/link-to}}
{{outlet}} 

Output

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

nested routes

When you click on link on the output, you will see the URL route as nestedroute/fruits and it will display the result from fruits.hbs −

nested routes

Previous Page:-Click Here

Leave a Reply