meteor – 设置文件标题

有没有办法改变meteor应用程序中的<title>元素? 似乎模板只能在<body>

在客户端JavaScript代码中的任何地方:

 document.title = "My new title"; 

您可以扩展David Wihl的解决scheme:

 Deps.autorun(function(){ document.title = Session.get("DocumentTitle"); }); 

那么你可以在任何时候打电话给:

 Session.set("DocumentTitle","New Document Title"); 

如果您使用iron:router,您可以添加包manuelschoebel:ms-seo来处理标题以及元标记。 这对静态和dynamicSEO数据很有用:

 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 } }); } }); }); 

你可以创build一个帮助器来设置标题(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>标签中包含不在模板中的标签。 尝试这个:

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被设置为反应,进入路由器文件(如果尚未完成:meteor add iron:router。我的路由器文件是客户端和服务器端)

 Router.route('/', { name: 'nameOfYourTemplate', onBeforeAction: function () { Session.set('documentTitle', 'whateverTitleIWant'); this.next(); //Otherwise I would get no template displayed } }); 

如果您已经在head标签中设置了标题,这并不重要。 根据你的路线它将被这个replace。

我不得不寻找一个适用于ui-router的答案。 我知道这可能不是你正在寻找的答案。 由于这个问题是在大约2年前发布的,我想如果有人来这里寻找ui-router的解决scheme,这个答案可以帮助他们:

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' } }) } })();