【发布时间】:2012-12-11 18:07:53
【问题描述】:
有没有办法在 Meteor 应用程序中更改 <title> 元素?似乎模板只在<body>中处理。
【问题讨论】:
标签: meteor
有没有办法在 Meteor 应用程序中更改 <title> 元素?似乎模板只在<body>中处理。
【问题讨论】:
标签: meteor
几乎在您的客户端 JavaScript 代码中的任何地方:
document.title = "My new title";
【讨论】:
您可以创建一个帮助器来设置标题(CoffeeScript):
UI.registerHelper "setTitle", ->
title = ""
for i in [0..arguments.length-2]
title += arguments[i]
document.title = title
undefined
或者在Js中相同:
UI.registerHelper("setTitle", function() {
var title = "";
for (var i = 0; i < arguments.length - 1; ++i) {
title += arguments[i];
}
document.title = title;
});
然后你可以以复杂的方式使用它,它会是响应式的:
{{#if book}}
{{setTitle book.title}}
{{else}}
{{setTitle "My books"}}
{{/if}}
【讨论】:
您可以扩展 David Wihl 的解决方案:
Deps.autorun(function(){
document.title = Session.get("DocumentTitle");
});
然后你可以随时调用:
Session.set("DocumentTitle","New Document Title");
【讨论】:
我发现用onBeforeAction直接在路由器中处理这种事情更方便:
Router.map(function() {
return this.route('StudioRoot', {
path: '/',
onBeforeAction: function() {
return document.title = "My Awesome Meteor Application";
}
});
});
【讨论】:
您还可以在<head> </head> 中包含不在模板中的标签。试试这个:
sample.html 的内容:
<head>
<title>my title</title>
</head>
<body>
...
</body>
<template name="mytemplate">
...
</template>
【讨论】:
如果您使用iron:router,您可以添加包manuelschoebel:ms-seo 来处理标题和元标记。这对于静态和动态 SEO 数据很有用:
Router.map(function() {
return this.route('blogPost', {
path: '/blog/:slug',
onAfterAction: function() {
var post = this.data().post;
SEO.set({
title: post.title,
meta: {
'description': post.description
},
og: {
'title': post.title,
'description': post.description
}
});
}
});
});
【讨论】:
我最终做了什么:
在 Meteor.isClient 中:
Meteor.startup(function() {
Deps.autorun(function() {
document.title = Session.get('documentTitle');
});
});
既然 var 是被动设置的,请进入路由器文件(如果尚未完成:meteor add iron:router。我的路由器文件既是客户端又是服务器)
Router.route('/', {
name: 'nameOfYourTemplate',
onBeforeAction: function () {
Session.set('documentTitle', 'whateverTitleIWant');
this.next(); //Otherwise I would get no template displayed
}
});
你是否已经在 head 标签中设置了一个标题并不重要。它将根据您的路线替换为这个。
【讨论】:
我必须寻找适用于 ui-router 的答案。我知道这可能不是您想要的答案。由于这个问题是大约 2 年前发布的,我想如果其他人来这里寻找 ui-router 的解决方案,这个答案可以帮助他们:
myApp.run.js
(function() {
'use strict';
angular
.module('myApp')
.run(run);
run.$inject = ['$rootScope', '$state'];
function run($rootScope, $state) {
$rootScope.$on("$stateChangeSuccess", function(previousRoute, currentRoute){
document.title = 'myApp - ' + currentRoute.data.pageTitle;
});
};
})();
routes.js
(function() {
'use strict';
angular
.module('myApp')
.config(config);
config.$inject =
['$urlRouterProvider', '$stateProvider', '$locationProvider'];
function config($urlRouterProvider, $stateProvider) {
// ...
$stateProvider
.state('home', {
url: '/',
templateUrl: 'client/home/views/home.ng.html',
controller: 'HomeController',
data: {
pageTitle: 'My Dynamic title'
}
})
}
})();
【讨论】: