2

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

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

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

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

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

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

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

4

2 回答 2

5

你应该像这样修改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>
于 2015-05-01T21:01:49.833 回答
0

我也需要这个功能,并发现了与@phocks 相同的问题,{{klass}}它只适用于内部而不适用于 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。在路径更改时,我得到nameI 声明的路由,从 body 标记中删除任何以前的路由名称,然后添加当前路由的名称。

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

于 2016-01-18T17:47:08.380 回答