在Meteor中改变基于URL的Body类
我的应用程序中有一个名为layout的模板。 里面有:
基本上我想要实现的是当你点击url时,例如www.abc.com/sky,我想添加一个蓝色的正文类:
在我的客户端文件夹中,我有这个,但似乎不起作用:
Template.layout.helpers({ blue: function() { var loc = window.location.href; // returns the full URL if(/sky/.test(loc)) { $('#body').addClass('blue'); } } });
我是javascript世界的新手,我正在学习一个教程,但教程并非针对Meteor。
你在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
看起来像这样:
我也需要这个function,发现@phocks与{{klass}}
phlass {{klass}}
相同的问题仅适用于内部标签,而不适用于主体标签。 我是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。 在路径更改时,我获取我为路由声明的名称,从body标签中删除任何先前的路由名称,然后添加当前路由的名称。
作为一个小旁注,我还为经过身份validation的用户添加了一类logged-in
到正文,这就是最后几行所做的事情。