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?
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';
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With