【问题标题】:Set HTML title when using iron-router使用 iron-router 时设置 HTML 标题
【发布时间】:2013-11-21 20:35:12
【问题描述】:

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

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

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

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

这不是很好。您对此有适当的解决方案吗?

【问题讨论】:

标签: javascript meteor handlebars.js iron-router


【解决方案1】:

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

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

编辑

如果您想在模板中设置标题,请创建自定义 Handlebars 助手(客户端代码):

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

并在你使用它的模板中使用它

{{KAZOOM 'example page'}}

{{KAZOOM}}

默认标题。

2015 年 7 月 26 日编辑:对于新的 Iron Router,它看起来像:

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

【讨论】:

  • 谢谢,这适用于静态标题。我仍然喜欢在模板中设置标题,就像所有其他文本一样
  • 为什么不使用这个包:iron-router-title
【解决方案2】:

我正在使用iron-router 0.7.1。

并在libs/router.js 中有这个

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

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

【讨论】:

  • this.route.getName() 现在,它出现了
【解决方案3】:

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

正如@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';
});

希望这会有所帮助。

【讨论】:

  • 对我来说最好的答案!遗憾的是,如果您在其中使用响应式 var,则不会重新评估 title 参数。如果您想要这种功能,最好的解决方案是什么?
猜你喜欢
  • 1970-01-01
  • 2015-01-24
  • 2016-10-31
  • 2015-03-12
  • 1970-01-01
  • 2014-01-16
  • 2014-07-11
  • 2018-10-04
  • 1970-01-01
相关资源
最近更新 更多