使用铁路由器时设置 HTML 标题
Set HTML title when using 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 标题,那就太好了。不幸的是,我没有看到实现这一目标的干净方法。我能想到的最接近的是命名 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';
});
希望这有帮助。
相关文章:
- 如何设置html元素填充的动画
- 使用val()在jquery循环中设置html字符串的val
- 在 PHP 块中使用 Javascript 设置 HTML 文本框的值(使用 echo)
- JS for循环来设置HTML对象参数
- 使用JavaScript在select字段中使用optgroup设置html选项值
- 使用jQuery在select选项上设置HTML数据属性
- 设置html时的验证
- 如何从javascript中设置html表单的属性
- 如何使用Angular 2设置HTML选择值
- 设置 HTML 自定义属性与在 ID 属性中存储信息
- 无法通过javascript函数的自动计算设置html元素值
- 通过单选按钮状态设置HTML元素的可见性
- 通过参数设置html组合框的选定选项
- 使用javascript设置html页面的标题
- 如何从javascript设置html单选值
- 通过单独的js文件设置HTML值
- 我们如何使用Jquery和ASP.NET MVC 4复杂模型数据设置HTML元素的值
- 如何使用来自@Html.TextBoxFor的用户输入设置@Html.RadioButtonFor的值
- ckEditor插件iframe对话框设置html输入
- 如何从json中设置HTML选择选项