【问题标题】:Change Body Class Based On URL in Meteor根据 Meteor 中的 URL 更改正文类
【发布时间】:2015-07-11 18:09:49
【问题描述】:

我的应用中有一个名为 layout 的模板。里面有:

<body id="body class="{{blue}}>

基本上我想要实现的是当你点击一个url时,例如,www.abc.com/sky,我想添加一个蓝色的body类:

<body id="body class="blue">

在我的 client 文件夹中,我有这个但似乎不起作用:

Template.layout.helpers({
  blue: function() {
    var loc = window.location.href; // returns the full URL
    if(/sky/.test(loc)) {
    $('#body').addClass('blue');
    }
  }
});

我是 javascript 世界的新手,我正在学习一个教程,但该教程并非针对 Meteor。

【问题讨论】:

  • 你用的是铁路由器吗?
  • 嗨 @DavidWeldon 是的,我是。

标签: jquery meteor meteor-helper


【解决方案1】:

你应该像这样修改onRendered中的DOM元素:

Template.layout.onRendered(function() {
  // get the current route name (better than checking window.location)
  var routeName = Router.current().route.getName();

  // add the class to body if this is the correct route
  if (routeName === 'myRoute')
    $('body').addClass('blue');
});

Template.layout.onDestroyed(function() {
  // remove the class to it does not appear on other routes
  $('body').removeClass('blue');
});

另一种(可能更简单)的解决方案是在您的 body 模板上使用帮助器:

Template.body.helpers({
  klass: function() {
    if (Router.current().route.getName() === 'myRoute') {
      return 'blue';
    }
  }
});

那么您的body 可能如下所示:

<body class="{{klass}}"></body>

【讨论】:

  • 完美运行。最后一个选项是最好的,因为顶部不喜欢被动反应。
  • 我的 html 中的 {{klass}} 似乎只有在它实际上位于 body 标记内时才有效......
  • Router.current().route.path() 为我工作。 (Router.current().route.getName() 没有)
【解决方案2】:

我也需要此功能,并发现与 @phocks 相同的问题在于 {{klass}} 仅适用于 inside 而不适用于 body 标签。我是 Meteor 的新手,但这是我只使用一些 jQuery 的方法:

Template.body.onRendered(function(){
    var instance = this;
    instance.autorun(function() {
        FlowRouter.watchPathChange();
        var context = FlowRouter.current();
        // this does the trick, below
        $('body').attr('class', '').addClass(context.route.name);   

        // this is just to do more CSS stuff if they're logged in
        if(Meteor.userId()){
            $('body').addClass('logged-in');   
        } else {
            $('body').removeClass('logged-in');   
        }
    });
});

我在body.js 文件中使用它,并且此代码依赖于FlowRouter。在路径更改时,我得到了为路由声明的 name,从 body 标记中删除任何以前的路由名称,然后添加当前路由的名称。

作为一个小说明,我还在正文中为经过身份验证的用户添加了一个 logged-in 类,这就是最后几行所做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多