javascript – 使用iron-router时设置HTML标题

前端之家收集整理的这篇文章主要介绍了javascript – 使用iron-router时设置HTML标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在使用铁路由器时最好地设置 HTML标题?这是我想做的事情:
  1. <template name="layout">
  2. <head><title>{{KAZOOM}}</title></head>
  3. <body>
  4. {{> menu}}
  5. {{yield}}
  6. </body>
  7. </template>
  8.  
  9. <template name="example">
  10. {{KAZOOM 'example page'}}
  11. That's just an example page
  12. </template>
  13.  
  14. <template name="foo">
  15. {{KAZOOM 'foo page'}}
  16. Another example page with different HTML title
  17. </template>

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

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

  1. <template name="head">
  2. <head><title>{{this}}</title></head>
  3. {{> menu}}
  4. </template>
  5.  
  6. <template name="example">
  7. {{> head 'example page'}}
  8. That's just an example page
  9. </template>
  10.  
  11. <template name="foo">
  12. {{> head 'foo page'}}
  13. Another example page with different HTML title
  14. </template>

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

解决方法

在Iron路由器中设置document.title onAfterRun:
  1. var pageTitle = 'My super web';
  2. Router.map(function() {
  3. this.route('user',{
  4. onAfterRun: function() {
  5. document.title = 'User ' + this.params.name + ' - ' + pageTitle;
  6. }
  7. });
  8. });

编辑:

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

  1. Handlebars.registerHelper("KAZOOM",function(title) {
  2. if(title) {
  3. document.title = title;
  4. } else {
  5. document.title = "Your default title";
  6. }
  7. });

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

  1. {{KAZOOM 'example page'}}

要么

  1. {{KAZOOM}}

默认标题.

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

  1. Router.route('/user',{
  2. onAfterAction: function() {
  3. document.title = 'page title';
  4. }
  5. });

猜你在找的JavaScript相关文章