0

In my app, I'm changing the page title per route. However, the page title is outside the main {{outlet}} I'm using, i.e:

application.handlebars:

<h1>{{pageTitle}}</h1>

{{outlet}}

I want to set pageTitle in the child controllers for each route, so this is what I'm doing:

App.WidgetsRoute = Ember.Route.extend
  setupController: (controller, model) ->
    @._super(controller, model)
    @controllerFor('application').set('pageTitle', 'Widgets')

Is this the right way to do this? I noticed a similar question, but the answer there didn't explain how to do this for titles that only change per-child controller and aren't necessarily calculable.

Community
  • 1
  • 1
nikz
  • 498
  • 4
  • 11

2 Answers2

2

You can have a setTitle action in your ApplicationRoute, which could set the pageTitle in the ApplicationController:

// routes/application.js
actions: {
  setTitle: function(title) {
    this.get('controller').set('title', title);
  }
}

and then maybe in the init function for a child route or controller. just send the action with the title you want, it should bubble up to the application route:

  init: function() {
    this.send('setTitle', 'My Page Title');
    this._super();
  },
Asgaroth
  • 4,274
  • 3
  • 20
  • 36
  • Is there a way to do that automatically? Or do I need to call that every time in the child controllers? – nikz Oct 27 '14 at 16:34
  • Just call it when you need to update the title, or you can create a base controller, that has this behavior by default that reads a `title` property. – Asgaroth Oct 27 '14 at 16:48
2

A slightly simpler way of doing this (which also seems to be implied by the docs) is this:

setupController: function(controller, model) {
    this._super(controller, model);

    this.controllerFor('application').set('pageTitle', 'Main title for page');
}

Edit

An even better way is using an initializer that reopens the Route class (assuming you use ember-cli, which you should)

// app/initializers/setup-route.js

import Ember from 'ember';

export function initialize() {
  Ember.Route.reopen({
    mainTitle: '',
    breadcrumbs: [],
    setupController: function(controller, model) {
      this._super(controller, model);

      var app = this.controllerFor('application');

      if(app) {
        app.set('mainTitle', this.mainTitle);
        app.set('breadcrumbs', this.breadcrumbs);
      }
    }
  });
}

export default {
  name: 'setup-route',
  initialize: initialize
};




// and in the route file

import Ember from 'ember';

export default Ember.Route.extend({
  mainTitle: 'Dashboard WIP',
});
Mihai Scurtu
  • 1,448
  • 1
  • 11
  • 22