将 Iron Router 与 Meteor.js 0.8.3 结合使用时,如何在 View 模板中包含根据用户所在路由而变化的文本?
例如,如果用户位于 /profile
,则文本将为 User Profile
,如果用户位于 /
,则文本将为 Home
。
header.html
<template name="header">
<h1>{{ routeTitle }}</h1>
</template>
profile.html
<template name="profile">
{{> header}}
</template>
router.js
Router.map( function() {
this.route('index', {
path: '/',
template: 'index'
})
this.route('profile', {
path: '/profile/:_id',
template: 'profile',
data: function() { return Users.findOne(this.params._id); }
})
})
最佳答案
我个人将我自己的属性存储在路由选项中,如下所示:
Router.map(function(){
this.route("index", {
// iron-router standard properties
path: "/",
// custom properties
title: "Home"
//
controller: "IndexController"
});
this.route("profile", {
path: "/profile/:_id",
title: "User profile",
controller: "ProfileController"
});
});
然后,我使用一组实用函数扩展路由器来访问当前路由。
_.extend(Router,{
currentRoute:function(){
return this.current()?this.current().route:"";
}
});
UI.registerHelper("currentRoute",Router.currentRoute.bind(Router));
使用这些实用程序,您可以在 JS 中调用 Router.currentRoute()
,它也恰好是一个响应式(Reactive)数据源,因为它充当 Router.current()< 的包装器
.
使用Router.currentRoute() && Router.currentRoute().options.title
检查是否存在当前路由并获取您在路由定义中声明的标题。
在模板中,您可以使用{{currentRoute.options.title}}
来获取当前标题,这在使用iron-router布局时很有帮助。
如果您想获得更具体的信息,您甚至可以模仿 Router.path
和 pathFor
辅助行为:
_.extend(Router,{
title:function(routeName){
return this.routes[routeName] && this.routes[routeName].options.title;
}
});
UI.registerHelper("titleFor",Router.title.bind(Router));
现在可以在JS中调用Router.title("index")
,在模板中调用{{titleFor "index"}}
。
您甚至可以为当前路线标题提供一个专门的帮助程序,正如您在问题中所建议的那样:
UI.registerHelper("currentRouteTitle",function(){
return Router.currentRoute() && Router.currentRoute().options.title;
});
关于javascript - Meteor.js Handlebar 根据 Iron Router 中的当前路线返回不同的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225725/