Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails 3.1 assets pipeline to conditionally use certain css

I've discovered a way to make it less rigid and future proof by still using the asset pipeline but having the stylesheets grouped. It's not much simpler than your solution, but this solution allows you to automatically add new stylesheets without having to re-edit the whole structure again.

What you want to do is use separate manifest files to break things up. First you have to re-organize your app/assets/stylesheets folder:

app/assets/stylesheets
+-- all
    +-- your_base_stylesheet.css
+-- print
    +-- blueprint
        +-- print.css
    +-- your_print_stylesheet.css
+-- ie
    +-- blueprint
        + ie.css
    +-- your_ie_hacks.css
+-- application-all.css
+-- application-print.css
+-- application-ie.css

Then you edit the three manifest files:

/**
 * application-all.css
 *
 *= require_self
 *= require_tree ./all
 */

/**
 * application-print.css
 *
 *= require_self
 *= require_tree ./print
 */

/**
 * application-ie.css
 *
 *= require_self
 *= require_tree ./ie
 */

Next you update your application layout file:

<%= stylesheet_link_tag "application-all", :media => "all" %>
<%= stylesheet_link_tag "application-print", :media => "print" %>

<!--[if lte IE 8]>
    <%= stylesheet_link_tag "application-ie", :media => "all" %>
<![endif]-->

Lastly, don't forget to include these new manifest files in your config/environments/production.rb:

config.assets.precompile += %w( application-all.css application-print.css application-ie.css )

Update:

As Max pointed out, if you follow this structure you have to be mindful of image references. You have a few choices:

  1. Move the images to follow the same pattern
    • Note that this only works if the images are not all shared
    • I expect this will be a non-starter for most since it complicates things too much
  2. Qualify the image path:
    • background: url('/assets/image.png');
  3. Use the SASS helper:
    • background: image-url('image.png');

Came across this problem today.

Ended up putting all IE specific stylesheets into lib/assets/stylesheets and creating one manifest file per version of IE. Then in application.rb add them to the list of things to precompile :

config.assets.precompile += ["ie9.css", "ie7.css", "ie8.css", "ie.css"]

And in your layouts, conditionally include those manifest files and you're good to go!


Thats a pretty neat way to do it. I use conditional classes on html or modernizr. See this article for a good representation on what does what. modernizr-vs-conditional-classes-on-html