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

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

问题描述

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

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

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

基本上,我想要实现的是当您键入一个网址(例如www.abc.com/sky)时,我想添加一个蓝色的主体类:

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.

推荐答案

您可以在 onRendered 像这样:

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>

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

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