How to generate url for a route in Ember.js

You can use Router#generate which delegates to the router.js library.

Ember 2.5 Example

App = Ember.Application.create();

App.Router.map(function() {
  this.resource('post', { path: '/posts/:post_id' }, function(){
    this.route('edit');
  });
});

App.Post = Ember.Object.extend();

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      App.Post.create({
        id: 5,
        title: 'I am post 5'
      }),
      App.Post.create({
        id: 6,
        title: 'I am post 6'
      }),
      App.Post.create({
        id: 7,
        title: 'I am post 7'
      })];
  },
  actions: {
    showUrl: function(post) {
      alert(this.router.generate('post.edit', post));
    }
  }
});

Ember 1.3 Example

App = Ember.Application.create();

App.Router.map(function() {
  this.resource('post', { path: '/posts/:post_id' }, function(){
    this.route('edit');
  });
});

App.Post = Ember.Object.extend();

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      App.Post.create({
        id: 5,
        title: 'I am post 5'
      }),
      App.Post.create({
        id: 6,
        title: 'I am post 6'
      }),
      App.Post.create({
        id: 7,
        title: 'I am post 7'
      })];
  },
  actions: {
    showUrl: function(post) {
      alert(this.router.generate('post.edit', post));
    }
  }
});

This is what the {{#link-to ...}} helper uses under the hood.


This can be done in any Ember.js class with the RouterService. It is available since Ember.js 2.15 and in 3.x. Routing functions are no longer confined to Routes.

Ember 2.15, 3.x Example

import Component from '@ember/component';
import { inject as service } from '@ember/service';

export default Component.extend({
  router: service(),

  actions: {
    showUrl(post) {
      alert(this.get('router').urlFor('post.edit', post));
    }
  }
});