是否有办法改变流星应用程序中的<title>
元素?似乎模板只在<body>
中处理。
几乎在您的客户端JavaScript代码的任何地方:
document.title = "My new title";
您可以扩展David Wihl的解决方案:
Deps.autorun(function(){
document.title = Session.get("DocumentTitle");
});
那么你可以在任何时候调用:
Session.set("DocumentTitle","New Document Title");
如果你使用iron:router,你可以添加manuelschoebel:ms-seo包来处理标题和meta标签。这对于静态和动态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
}
});
}
});
});
你可以创建一个助手来设置标题(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}}
我发现用onBeforeAction
直接在路由器中处理这种事情更方便:
Router.map(function() {
return this.route('StudioRoot', {
path: '/',
onBeforeAction: function() {
return document.title = "My Awesome Meteor Application";
}
});
});
您还可以在<head> </head>
标记中包含不驻留在模板中。试试这个:
content of sample.html:
<head>
<title>my title</title>
</head>
<body>
...
</body>
<template name="mytemplate">
...
</template>
我最后做了什么:
在Meteor.isClient:
Meteor.startup(function() {
Deps.autorun(function() {
document.title = Session.get('documentTitle');
});
});
现在var已经设置好了,进入router文件(如果还没有完成的话):我的路由器文件是客户端和服务器)
Router.route('/', {
name: 'nameOfYourTemplate',
onBeforeAction: function () {
Session.set('documentTitle', 'whateverTitleIWant');
this.next(); //Otherwise I would get no template displayed
}
});
如果你已经在head标签中设置了标题也没关系。
我必须寻找一个适用于ui-router的答案。我知道这可能不是你想要的答案。因为这个问题是大约2年前发布的,我想如果有人来这里寻找一个解决方案,这个答案可以帮助他们:
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'
}
})
}
})();