EmberJS – Router Dynamic Segment

  • Post author:
  • Post category:EmberJS
  • Post comments:1 Comment

A dynamic segment begins with a “:” in route() method followed by an identifier. The URL is defined with an id property in the model.

Syntax

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

Example

The below example shows how to use dynamic segments for displaying data. Open the file created under app/templates/. Here, we have created the file as blog-post.hbs with the below code −

<h2>My Profile</h2>
Hello

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('blog-post', { path: '/blog-post/:username'});
});

export default Router;

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

{{#link-to 'blog-post' 'smith'}}View Profile{{/link-to}}
{{outlet}}

To construct the URL, you need to implement the serialize hook which passes the model and returns the object with dynamic segment as the key.

import Ember from 'ember';

export default Ember.Route.extend ({
   model: function(params, transition) {
      return { username: params.username }; 
   },
   
   serialize: function(model) {
      return { username: model.get('username') }; 
   }
});

Output

Run the ember server and you would get the below output −

dynamic segment

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 −

dynamic segment

Previous Page:-Click Here

This Post Has One Comment

Leave a Reply