Names of routes to use as a title reachable from router


#1

What would be the best way to implement additional names to routes in the router to get them in components?

What it might look like:

Router.map(function() {
  this.route('about', {title:'About us', path:'/about'});
  this.route('first', {title:'First Page', path:'first-page'});
  this.route('second', {title:'Second awesome page', path:'second-page'});
});

Then in component I would like to get it in a similar to the following way:

export default Ember.Component.extend({
   routing: Ember.inject.service('-routing'),
   title: Ember.computed('routing.currentRoute.title', function() {

       let routeTitle = this.get('routing.currentRoute.title');
       
       return routeTitle;
   })
});

What I tried but feel it is not the best way at all, I get currentRoute with “routing.currentRouteName” and then conditionally return needed title, similar to this:

   let routes = {
       "about": "About us",
       "first-page": "First Page",
       "second-page": "Second Awesome Page"
   }

   let routeTitle = this.get('routing.currentRouteName');
   
   return routes[routeName];

I’m thinking it is also possible to use observables but I would like to see the right way of doing this in Ember.


#2

Sounds like you’re trying to setup a solution for the document/browser title.?. I’d suggest taking a look at one of the two common ember addons. They take different approaches so which is the best fit will depend on your needs. I have experience with the first one if you have questions, but the second in an intriguing option as well.

https://emberobserver.com/addons/ember-cli-document-title https://emberobserver.com/addons/ember-page-title


#3

Thank you, I tried the first addon, however, I need it to be not only in the document title but also I want to use it in a header. Also it would be nice to get full list of the titles of all the routes, this list could be then used in navigation menu, hence I think the source of all the routes and their titles should be in one place, i.e. in the router, but I might be wrong and there are better practices.


#4

You could use that first option and then using the title hook .set() all the tokens on the controller.

I’ve also “hacked” my own solution before but worry that it’ll break with router updates. I can provide some info but have to get going now. As a start, here is my “hack” on getting active routes: https://gist.github.com/Panman8201/7f27b083376e7447b3c4


#5

Well, it is a bit complicated for me now since I’ve just started with Ember, I’m not sure how to use reopen() and how to use initializers, should read about all of that first. Anyway, ember-cli-document-title works fine for me. I get back to this when I am more proficient with basics of Ember. Thank you!