Search code examples
node.jsmeteoriron-router

How can I add a class to iron router default template?


I've been searching all over and haven't really found an answer to this seemingly very simply problem.

I have an app that has a default template

Router.configure({
layoutTemplate: 'appLayout',
});

<template name="appLayout">
  <div id="container">
    {{> yield}}
  </div>
</template>

Then I have a new route called 'reservations'

Router.route('/reservations',{
name:'reservations',
  onAfterAction: function(){

  }
});

What I'd like to do is add a class to the default container that uses css transitions to animate background color from white to black.

What I've tried so far is onAfterAction

Router.route('/reservations',{
name:'reservations',
onAfterAction: function(){
    $('#container').addClass('black');
}
});

Does nothing, no errors, no anything. So I've tried

Template.reservations.rendered = function () {
setTimeout(function(){
    $('#container').addClass('black');
});
};

Which works, but flashes and creates routing problems. You can see the routing issues at crawfish.meteor.com. How can I simply toggle a class after the template is rendered?


Solution

  • You can use the rendered event:

    Template.reservations.rendered = function() {
        if( ! this.rendered) {
            $('#container').addClass('black');
            this.rendered = true;
        }
    };
    

    Note that we check and set rendered. The Template instance then has a 'rendered' variable that we use to prevent re-triggering on re-render (which can run multiple times)