Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set HTML title when using iron-router

How to best set the HTML title when using iron-router? Here's what I'd like to do:

<template name="layout">
    <head><title>{{KAZOOM}}</title></head>
    <body>
        {{> menu}}
        {{yield}}
    </body>
</template>

<template name="example">
    {{KAZOOM 'example page'}}
    That's just an example page
</template>

<template name="foo">
    {{KAZOOM 'foo page'}}
    Another example page with different HTML title
</template>

You see how the KAZOOM travels back in time to set the HTML title? The reason I wish to do it that way is that I consider the HTML title to be part of the content. It would be nice I could adjust the HTML title of a page by just editing the template that generated it. Unfortunately I don't see a clean way to achieve this. The closest I can think of would be named yields, then the title would be set by the route, not by the template.

The other possibility is to just forgo the layout template and always include a header:

<template name="head">
    <head><title>{{this}}</title></head>
    {{> menu}}
</template>

<template name="example">
    {{> head 'example page'}}
    That's just an example page
</template>

<template name="foo">
    {{> head 'foo page'}}
    Another example page with different HTML title
</template>

That is not very nice. Do you have a proper solution to this?

like image 465
sba Avatar asked Nov 09 '13 20:11

sba


1 Answers

Set document.title onAfterRun in Iron router:

var pageTitle = 'My super web';
Router.map(function() {
   this.route('user', {
      onAfterRun: function() {
        document.title = 'User ' + this.params.name + ' - ' + pageTitle;
      }
   });
});

EDIT:

If you want to set title in template, create custom Handlebars helper (client code):

Handlebars.registerHelper("KAZOOM", function(title) {
    if(title) {
        document.title = title;
    } else {
        document.title = "Your default title";
    }
});

And use it in your templates as you used it

{{KAZOOM 'example page'}}

or

{{KAZOOM}}

for default title.

EDIT 26 Jully 2015: for new Iron Router it would look like:

Router.route('/user', {
  onAfterAction: function() {
    document.title = 'page title';
  }
});
like image 61
Tomas Hromnik Avatar answered Nov 15 '22 07:11

Tomas Hromnik