使用铁路由器时设置 HTML 标题

Set HTML title when using iron-router

本文关键字:设置 HTML 标题 路由器      更新时间:2023-09-26

使用铁路由器时如何最好地设置HTML标题?以下是我想做的:

<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>

您会看到 KAZOOM 如何回到过去以设置 HTML 标题吗?我希望这样做的原因是我认为HTML标题是内容的一部分。我可以通过编辑生成页面的模板来调整页面的 HTML 标题,那就太好了。不幸的是,我没有看到实现这一目标的干净方法。我能想到的最接近的是命名 yields,然后标题将由路由设置,而不是由模板设置。

另一种可能性是放弃布局模板并始终包含一个标题:

<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>

这不太好。你有适当的解决方案吗?

在 Iron router 中设置 document.title onAfterRun:

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

编辑

如果要在模板中设置标题,请创建自定义车把帮助程序(客户端代码):

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

并在使用模板时使用它

{{KAZOOM 'example page'}}

{{KAZOOM}}

作为默认标题。

编辑2015年7月26日:对于新的铁路由器,它看起来像:

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

我使用的是 0.7.1 iron-router

并有这个libs/router.js

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

它处理我的所有路线,所以我不必把它放在每条路线中。

我更喜欢将标题属性与路由定义一起存储。

正如@nullpo在这个问题上所建议的那样 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';
});

希望这有帮助。