Controller Based Stylesheets

August 14th, 2007

This one is a pretty simple method for organizing and serving specific stylesheets based on what controller your application is currently serving. A friend of mine has written a nice plugin for this, but there is an even easier way to do this:

In your application helper file add:

1
2
3
4
5
6
  def add_stylesheets
    stylesheet = File.join(controller.controller_name, controller.controller_name + ".css")
    if File.exists? File.join(RAILS_ROOT, "public/stylesheets", stylesheet)
      return stylesheet_link_tag(stylesheet, :media => "screen, projection")
    end  
  end

Add to your layout header:


  <%= add_stylesheets %>

I use this in conjunction with:

1
2
3
4
  def body(options={}) 
      options = { :id => controller.controller_name, :class => controller.action_name }.merge(options)   
      tag('body', options, true) 
  end

Patrick’s version goes a bit more granular than my take on it above.

In the example above, I’m assuming you have a directory (public/stylesheets/controller_name/) that is named after your controller which holds the controller specific CSS file. (public/stylesheets/controller_name/controller_name.css) One, this helps organize your CSS in the stylesheets directory and 2) it allows you to separate out your CSS files for easier maintainability and 3) it only loads that controllers CSS file instead of one big file for the whole application (you can of course add more stylesheets for the core of your app in the normal rails way).

Here at work, our CSS files were starting to get rather large and we didn’t need to load those files for every controller – it was just a waste of bandwidth and maintaining them was becoming a headache. Now we just have a couple core “type” files and our controller specific CSS files.

Sorry, comments are closed for this article.