Change Body Class Based On URL in Meteor

前端 未结 2 1919
臣服心动
臣服心动 2021-01-07 04:03

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


Basically what I want to ach

2条回答
  •  独厮守ぢ
    2021-01-07 04:13

    I too needed this feature and found the same issue as @phocks in that {{klass}} only works inside and not on the body tag. I'm new at Meteor but here's my approach that just uses some 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');   
            }
        });
    });
    

    I use this in a body.js file, and this code relies on FlowRouter. On path changes, I get the name I declared for the route, remove any previous route names from the body tag, then add the current route's name.

    As a small side note, I also add a class of logged-in to the body for authenticated users, so that's what the bottom few lines are doing.

提交回复
热议问题