使用iron-router时设置HTML标题

sba*_*sba 6 javascript handlebars.js meteor iron-router

如何在使用铁路由器时最好地设置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>
Run Code Online (Sandbox Code Playgroud)

你看到KAZOOM如何及时回归来设置HTML标题?我希望这样做的原因是我认为HTML标题是内容的一部分.我可以通过编辑生成它的模板来调整页面的HTML标题.不幸的是,我没有看到实现这一目标的干净方法.我能想到的最接近的是命名率,然后标题将由路径设置,而不是由模板设置.

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

<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>
Run Code Online (Sandbox Code Playgroud)

那不是很好.你有适当的解决方案吗?

Tom*_*nik 16

在Iron路由器中设置document.title onAfterRun:

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

编辑:

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

Handlebars.registerHelper("KAZOOM", function(title) {
    if(title) {
        document.title = title;
    } else {
        document.title = "Your default title";
    }
});
Run Code Online (Sandbox Code Playgroud)

并在使用它时在模板中使用它

{{KAZOOM 'example page'}}
Run Code Online (Sandbox Code Playgroud)

要么

{{KAZOOM}}
Run Code Online (Sandbox Code Playgroud)

默认标题.

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

Router.route('/user', {
  onAfterAction: function() {
    document.title = 'page title';
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用这个包:[iron-router-title](https://atmospherejs.com/ostrio/iron-router-title)? (3认同)

rus*_*eed 10

我正在使用iron-router0.7.1.

并且有这个 libs/router.js

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

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