Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember - Set a Dynamic Page Title per route

I have set up my Ember app to use the pod structure. I've created a topbar-nav component which I display on the main page. In the topbar-nav component I have set up the page title, which I would like to set automatically per route so for the dashboard route the title should be Dashboard, for the dashboard/categories the title should be categories and so on.

Here's my app structure:

  • app
    • application
    • components
      • topbar-nav
    • dashboard
    • categories

The app router - router.js

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('dashboard', function() {
    this.route('categories');
  });
});

export default Router;

And the templates:

application/template.hbs

<aside>
    {{sidebar-nav}}
</aside>

<main>
    <header>
        {{topbar-nav}}
    </header>

    {{outlet}}
</main>

components/topbar-nav/template.hbs

<nav class="topbar-nav">
    <div class="text-center">
        <h5 class="page-title">{{title}}</h5>
    </div>
</nav>

{{yield}}

components/topbar-nav/component.js

import Ember from 'ember';

export default Ember.Component.extend({
    title: 'Component title'
});

As you can tell already the title I get rendered is 'Component title'

The most accurate answer I got by now is this one:

Ember dynamic titles

though after trying a lot of different approaches I couldn't find a good solution.

Is there a clean and easy way of doing this? Any ideas and solutions are much appreciated.

like image 388
Sabin Avatar asked Oct 30 '22 20:10

Sabin


1 Answers

I wanted a similar dynamic title and found this page. So here is my solution based on @AcidBurn's note that the application controller has a currentRouteName property.

If you want the last child route:

screen_title: Ember.computed('currentRouteName', function () {
    let route = this.get('currentRouteName').split('.');

    // Return last route name (e.g. categories from dashboard.categories)
    return route[route.length - 1];
}),

If you want the parent route:

screen_title: Ember.computed('currentRouteName', function () {
    let route = this.get('currentRouteName').split('.');

    // Return parent route name (e.g. reports from reports.index)
    return route[0];
}),
like image 91
Vlad Avatar answered Jan 04 '23 15:01

Vlad