js车把根据当前路由返回不同的文本
Meteor.js Handlebar Returns different Text depending on current Route in Iron Router
使用Iron Router with 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"
});
});
然后我用一组实用程序函数扩展Router来访问当前路由。
_.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.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;
});
您可以很容易地实现这一点,使用路径的data
参数:
Router.map(function() {
this.route('...', {
...
data: function() {
return {
importantText: 'User Profile',
};
},
});
});
现在将其用作渲染模板、布局模板或任何渲染到命名区域的模板中的任何其他数据对象:
{{importantText}}
相关文章:
- 在HTML表单中键入时返回文本
- 返回文本区域的原始上下文菜单
- 简单的js替换并返回文本
- jquery ajax不会在出现错误时返回文本和/或火警警报
- 如何在ajax中返回文本文件值Asynchronous"Synchronous正在被弃用”;
- 将文本更改为输入并返回文本
- 如何从保留换行符的 window.prompt() 返回文本
- 无法使用 AJAX 获取 url 的 StumbleOn 视图,因为它的 API 返回文本/纯文本
- SVG 子节点返回文本
- 访问选项对象(在 ngSelect 中使用),但仅返回文本框中的特定值
- 如何使用 Ionic 返回文本框的值
- getSelection在清除后返回文本
- JavaScript返回文本+播放声音
- xmlrequest不会从php返回文本
- 为什么ajax调用失败.下面的代码重定向到authenticate.php,而不是返回文本到login.html
- Jquery的val()不会返回文本框的值
- 美元.getJSON失败,但返回文本
- nodeValue不返回文本
- jQuery根据标签标签从span标签返回文本
- 通过HTTP请求返回文本文件作为数组javascript