流星js的iron router:当路由发生变化时,应用CSS更改

meteor js iron router: apply CSS change whenever route changes

本文关键字:变化 应用 更改 CSS 路由 js iron router 流星      更新时间:2023-09-26

我的应用程序中有主页,联系人页面和其他几个产品相关页面。

目标是将背景图像仅应用于特定路线:/homepage/contact

我现在在我的主页上与一个助手一起破解这个,像这样:

Template.homepage.rendered = function () {
    var route = Router.current();
    if ( route.path == '/' ) {
        document.body.className = "showBackgroundImage";
    }
};

部分获胜,因为这将激活css,但我需要在路由改变时停用。我还在我的router.js中尝试了以下操作:

this.route('homepage', {
    path: '/', 
    onAfterAction: function  (argument) {
       // add a class name to body
       document.body.className = "showBackgroundImage";
    }
  });

和CSS的背景标准:

.showBackgroundImage { 
  background: url(bgImage.jpg) no-repeat center center fixed; 
}

使用iron:router布局和通过路由为每个页面应用不同的类很容易做到。

首先你需要定义一个主布局,如:

<template name="mainLayout">
  <!-- optional navbar yield -->
  {{> yield region="navbar"}}
  <div class="{{currentRouteName}}-page">
    {{> yield}}
  </div>
  <!-- optional footer yield -->
  {{> yield region="footer"}}
</template>

currentRouteName助手应该看起来像:

UI.registerHelper("currentRouteName",function(){
  return Router.current()?Router.current().route.getName():"";
});

然后我建议将RouteController关联到您的主布局,它将作为所有RouteController的基类。

MainController=RouteController.extend({
  layoutTemplate:"mainLayout",
  // yield navbar and footer templates to navbar and footer regions respectively
  yieldTemplates:{
    "navbar":{
      to:"navbar"
    },
    "footer":{
      to:"footer"
    }
  }
});

接下来,你需要确保你的路由使用的控制器是从MainController派生出来的。

HomeController=MainController.extend({
  template:"home"
});
Router.map(function(){
  this.route("home",{
    path:"/",
    // optional, by default iron:router is smart enough to guess the controller name,
    // by camel-casing the route name and appending "Controller"
    controller:"HomeController"
  });
});

现在你的主页被一个div包围了,这个div有一个"home-page"类,所以你可以用普通的CSS样式(或者更好的是,使用LESS):

.home-page{
  /* your css goes here */
}

如果你定义了其他路由,这将无缝地工作,只要从MainController继承,你就会自动拥有一个带有route-name-page类的页面。

当然,你可以对多个页面使用相同的样式,只要在CSS中指定:
.home-page, .contact-page{
  /* your css goes here */
}

你可以用布局做一些很好的事情,我强烈建议你使用它们。

我已经使用iron-routerjQuery做了这个确切的事情。我是这么做的。

/**
 * Add a background image for certain routes.
 */
var setBackground = function () {
  var route = this.route.name;
  var routes = ['homepage', 'contact'];
  if (_.contains(routes, route)) {
    $('body').addClass('showBackgroundImage');
  } else {
    $('body').removeClass('showBackgroundImage');
  }
};
Router.onBeforeAction(setBackground);

使用Meteor 1.2iron-router,这对我来说是非常容易的:

Router.onBeforeAction(function() {
  $('body').addClass(this.route.options.template);
  this.next();
});

就是这样!

这将从您正在使用的模板中获取名称并将其分配给正文。

多么容易和方便!!

如果你想指定一个特定的名称而不是模板名称,只需将this.route.options.template替换为this.route.getName()并为你的路由指定一个名称。