<title>
Meteor アプリで要素を変更する方法はありますか? テンプレートは でのみ処理されるよう<body>
です。
8 に答える
クライアント側の 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を追加して、タイトルとメタ タグを処理できます。これは、静的および動的な 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";
}
});
});
私がやったこと:
Meteor.isClient で:
Meteor.startup(function() {
Deps.autorun(function() {
document.title = Session.get('documentTitle');
});
});
変数が反応的に設定されたので、ルーターファイルに移動します(まだ行っていない場合: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;
});
};
})();
ルート.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'
}
})
}
})();