When I first came in touch with Ember.js to build the client-side rendered version of Muffin, I was looking for a way to add the name of the currently active route to the body. I needed it because I wanted certain styles to only be applied to the elements within a certain route.

So after looking around the web for a few minutes, I’ve found ember-body-class — an add-on which does exactly that. If you just want to take advantage of the body classes that are based on the route name, you don’t even need to configure a single thing!

And what’s even more awesome is that you can easily extend the list of classes by simply adding them to an array available under the “className” property:

export default Ember.route.extend({
  classNames: ['strawberry-jam']
})

So all in all a pretty great solution, right? Definitely!

But yesterday, I took some of my time and decided to kick out some of the add-ons that aren’t really needed. Mostly because each of them of course adds another big bag of code to the compiled Ember app.

So after looking for ways to solve this problem within an additional add-on, I came across DockYard’s solution. It picks the name of the current route (“users.edit” for example), replaces all dots with dashes and finally adds it to the body’s “class” attribute.

However, I wanted a solution that mimics the behaviour of ember-body-class. What I mean with this is that the parts of the route (“users” and “edit”) shouldn’t be treated as a single class named “users-edit”, but rather added to the body as separate classes.

Because of this, I came up with a improved solution:

I’ve generated a new initializer and called it “setup-route”. Then I’ve added the following methods to it:

Ember.Route.reopen({
  activate () {
    var classes = this.genClasses()

    if (classes !== 'application') {
      Ember.$('body').addClass(classes)
    }
  },
  deactivate () {
    Ember.$('body').removeClass(this.genClasses())
  },
  genClasses () {
    var classes = this.routeName.split('.')

    if (this.classNames) {
      for (var name of this.classNames) {
        classes.push(name)
      }
    }

    return classes.join(' ')
  }
})

So there you have it!

The easiest way to add the name of the current route as a class to the body, without an add-on. It completely imitates the behaviour of ember-body-class and even allows you to extend the list of classes by using the “classNames” property on your route.