2

I have a template named layout in my app. Inside has:

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

Basically what I want to achieve is that when you hit a url, for example, www.abc.com/sky, I want to add a body class of blue:

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

In my client folder I have this but seems not to work:

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

I am new to the javascript world and I am following a tutorial but the tutorial was not aimed for 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 に答える