New API for document titles


(Robin Ward) #1

Ember is not completely congruous with the concept of a “page.” Its router allows you to nest outlets with their own data models and templates. This made it tricky for us to have a common API for setting the title of a document.

This became a problem when we wanted to submit the current “page title” to google analytics (or any other analytics package, really); after our router transitioned to another route, we knew it was time to tell google analytics about the change, but we didn’t always have the title at that time.

Today I came up with a solution that makes it a lot easier to set page titles, and they will be passed directly through to the PageTracker api for analytics.

In any route class you can create a titleToken method. If it returns a token, it will be used in the title. If no token is supplied or null is returned, it will just go up the chain of routes to the parent and try that one, and so on.

A token is a segment of the title. Just return a string (or an array of tokens) and it will be joined together once the router finishes transitioning.

So for example in the Topic route class:

titleToken: function() {
  var model = this.modelFor('topic');
  if (model) {
    return model.get('title');
  }
},

If there is a current topic model (really just a safeguard) we return its topic title.

The application is smart enough to collect the tokens in the order we display them, so first the Topic route will be called, then its parent and so on until the application route is called.

The application route always has the default of your Discourse install’s title, so that will always be included. So when viewing a title it will look like “My cool title - Discourse Meta”

P.S. Thanks to machty for the inspiration.