Meteor.js Handlebar根据Iron Router中的当前路由返回不同的文本

在Meteor.js 0.8.3中使用铁路路由器时,如何在视图模板中有一个文本取决于用户在哪个路由上进行更改?

例如,如果用户在/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" }); }); 

然后,我用一组实用程序function扩展路由器以访问当前路由。

 _.extend(Router,{ currentRoute:function(){ return this.current()?this.current().route:""; } }); UI.registerHelper("currentRoute",Router.currentRoute.bind(Router)); 

使用这些实用程序,您可以调用JS中的Router.currentRoute() ,这恰好也是一个被动数据源,因为它充当Router.current()的包装器。

使用Router.currentRoute() && Router.currentRoute().options.title检查是否存在当前路由并获取您在路由定义中声明的标题。

在模板中,您可以使用{{currentRoute.options.title}}来获取当前标题,这在使用铁路路由器布局时很有用。

如果你想得到更具体的,你甚至可以模仿Router.pathpathFor辅助者的行为:

 _.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"}}

您甚至可以像您在您的问题中所build议的那样,为当前的路线标题提供专门的帮助:

 UI.registerHelper("currentRouteTitle",function(){ return Router.currentRoute() && Router.currentRoute().options.title; }); 

您可以非常容易地使用path的data参数来实现:

 Router.map(function() { this.route('...', { ... data: function() { return { importantText: 'User Profile', }; }, }); }); 

现在将它用作渲染模板,布局模板或渲染到指定区域的任何模板中的任何其他数据对象:

 {{importantText}}