Set HTML header when using iron router

What is the best way to customize the HTML header when using an iron router? Here is what I would like to do:

<template name="layout"> <head><title>{{KAZOOM}}</title></head> <body> {{> menu}} {{yield}} </body> </template> <template name="example"> {{KAZOOM 'example page'}} That just an example page </template> <template name="foo"> {{KAZOOM 'foo page'}} Another example page with different HTML title </template> 

Do you see KAZOOM returning on time to set the HTML header? The reason I want to do this is because I believe the HTML header is part of the content. It would be nice if I could change the page title on the page by simply editing the template that generated it. Unfortunately, I do not see a clean way to achieve this. The closest I can think of will be called yields, then the header will be set by the route, not the pattern.

Another possibility is to simply abandon the layout template and always include the title:

 <template name="head"> <head><title>{{this}}</title></head> {{> menu}} </template> <template name="example"> {{> head 'example page'}} That just an example page </template> <template name="foo"> {{> head 'foo page'}} Another example page with different HTML title </template> 

This is not very nice. Do you have the right solution?

+6
source share
3 answers

Set document.title onAfterRun to 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 the title in the template, create a special 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 the default header.

EDIT July 26, 2015: for the new Iron Router, it will look like this:

 Router.route('/user', { onAfterAction: function() { document.title = 'page title'; } }); 
+16
source

I am using iron-router 0.7.1.

And let it in libs/router.js

 Router.onAfterAction(function() { document.title = 'My Site - '+this.route.name; } ); 

which handles all my routes, so I don’t need to point it on every route.

+10
source

I prefer to have the title attribute stored correctly with the route definition.

As suggested by @nullpo on this issue https://github.com/iron-meteor/iron-router/issues/292#issuecomment-38508234

 Router.route('/admin/users', { name: 'admin_users', template: 'admin_users', title: 'User Manager' data: function() { return Meteor.users.find(); }, waitOn: function() { return Meteor.subscribe('users_admin'); } }); Router.after(function(){ if (this.route.options.title) document.title = this.route.options.title + ' - my cool site'; }); 

Hope this helps.

+3
source

Source: https://habr.com/ru/post/957751/


All Articles