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

标签 javascript node.js meteor handlebars.js

将 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.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;
});

关于javascript - Meteor.js Handlebar 根据 Iron Router 中的当前路线返回不同的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225725/

相关文章:

javascript - 在 node.js 中使用按键启动操作

javascript - 如何让 toJSON 在返回 Sails.js 中的对象之前等待查找?

JavaScript 数组过滤和映射会在数组条目之间产生逗号吗?

meteor - W20141104-19 :23:53. 848(5.5)? (STDERR) 错误 : EBADF, 读取 - meteor js 错误

collections - meteor collection.update权限

Javascript:如何通过 Firefox 浏览器从 API 服务器下载 zip?

node.js - 使用 Node JS 在哪里存储 CMS 图像?

javascript - 在 catch block nodejs/javascript 中有 promise 问题

mysql - Migrations 在指定列和索引列之后添加列

javascript - meteor 模板中的简单数据反射