3

I need to generate the url for given route from a helper.

How to generate url for a route in Ember.js pointed me to use the generate function. And yes it works as i need (Checked the functionality by making application route global). But i am not sure how to call it from inside a helper.

Community
  • 1
  • 1
acid_srvnn
  • 693
  • 8
  • 15

1 Answers1

3

You were in a good direction, so you mainly solved this problem. :) There are two type of helper in Ember a simple function helper and the Class Based Helpers. We will use a Class Based Helper in this case.

As you have seen in your linked example, we need access to the main Router. We can do this with Ember.getOwner(this).lookup('router:main'). (Ember.getOwner() exists from v2.3, before v2.3 use this.container.lookup('router:main'))

For example, you have this map in your router.js:

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

And if you create a helper for example with the name of url-for your template could contain these lines:

{{url-for 'about'}}
{{url-for 'posts'}}
{{url-for 'posts.post' 2}}

And your Class Based Helper could be the following:

// app/helpers/url-for.js
import Ember from 'ember';

export default Ember.Helper.extend({
  router: Ember.computed(function() {
    return Ember.getOwner(this).lookup('router:main');
  }),

  compute([routeName, ...routeParams]) {
    let router = this.get('router');

    return Ember.isEmpty(routeParams) ?
      router.generate(routeName) : router.generate(routeName, routeParams[0]);
  }
});

Demo on Ember Twiddle

Zoltan
  • 4,936
  • 1
  • 35
  • 40