What is the definitive way to manage the document title?


#1

There seems to be a lot of conflicting answers about how to manage the document title when the route changes. Normally I wouldn’t have a problem with just doing document.title = 'Blah' but I can’t seem to find a good point in the route object to even definitely set this, or an appropriate hook.

What I would like to be able to do is something like this…

App.ArticleRoute = Ember.Route.extend({

    model: function(params) {
        //return data
    }

    title: function(params) {
        return 'Super Awesome Article'; // <--- this becomes the page title
    }

});

Or something. Thoughts?


Standard way to set page title
#2

http://emberjs.com/api/classes/Ember.Route.html#method_activate

App.ArticleRoute = Ember.Route.extend({
  activate: function() {
    document.title = "Super Awesome Article";
  }
});

#3

Yes, but isn’t the “activate” function only entered the first time that the route is accessed? So this would only work for the first time a user visits the route.


#4

I think activate is hit every time a route is entered, but doesn’t get called if the model changes. So if you need your title to change based on the model you may want to do it has an an observable.

App.ArticleController = Ember.ObjectController.extend({
  updateTitle: function() {
    window.title = 'Viewing - ' + this.get('articleTitle');
  }.observes('model.articleTitle')
});

#5

Relevent PR: https://github.com/emberjs/ember.js/pull/2757


#6

That pull request would make things a lot easier, although I do like @raytiley’s method, since you can use model data. Thanks, guys.


#7

There is an old annoying chrome bug in this department:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse.js#L47-L53


#8

I noticed that in the Discourse app class when I was researching this - I’m still confused a bit on how Discourse is managing the title; I see that titleChanged is observing ‘title’ but where are you actually pushing title changes? Haven’t found them anywhere.


#9

Look for all the Discourse.set('title', ...) calls :wink:


#10

Believe it or not I hunted high and low for those. :confused: Never saw them until today! Gah!!

Thanks for the tips, everyone.


#11

See https://github.com/emberjs/ember.js/pull/3689 for a PR in progress for document.title integration into ember.