在 Meteor 中根据 URL 更改正文类 [英] Change Body Class Based On URL in Meteor

查看:20
本文介绍了在 Meteor 中根据 URL 更改正文类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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">

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

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');
    }
  }
});

我是 JavaScript 世界的新手,我正在学习教程,但该教程并非针对 Meteor.

I am new to the javascript world and I am following a tutorial but the tutorial was not aimed for Meteor.

推荐答案

您不得修改 中的 DOM 元素onRendered 像这样:

You shold modify DOM elememts in onRendered like this:

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 模板上使用帮助程序:


An alternative (and probably easier) solution is just to use a helper on your body template:

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

那么你的 body 可能看起来像这样:

Then your body could look like this:

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

这篇关于在 Meteor 中根据 URL 更改正文类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆