js车把根据当前路由返回不同的文本

Meteor.js Handlebar Returns different Text depending on current Route in Iron Router

本文关键字:返回 文本 路由 js      更新时间:2023-09-26

使用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.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"}}

你甚至可以为当前路由标题提供一个专用的助手,正如你在问题中建议的那样:

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

您可以很容易地实现这一点,使用路径的data参数:

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

现在将其用作渲染模板、布局模板或任何渲染到命名区域的模板中的任何其他数据对象:

{{importantText}}