Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage CSS Stylesheet Assets in Rails 3.1?

Tags:

I'm just learning the new asset pipeline in Rails 3.1. One particular problem I'm having is with the way Sprockets just mashes all the found CSS stylesheets into one massive stylesheet. I understand why this is advantageous over manually merging stylesheets and minifying for production. But I want to be able to selectively cascade stylesheets instead of having all rules all mashed together. For instance, I want:

master.css

to be loaded by all pages in the Rails app, but I want

admin.css only to be loaded by pages/views within the admin section/namespace.

How can I take advantage of the great way that Rails 3.1 combines stylesheets and minifies them for production, but also have the former flexibility of being able to load only certain stylesheet combinations per layout?

Or should this be done by adding a class to body tags in layouts-

body class="admin"

And then target style rules as appropriate. Using SASS scoped selectors this might be a reasonable solution.

like image 464
Ben Avatar asked May 23 '11 19:05

Ben


People also ask

How do you use assets in Rails?

You should use app/assets for files that must undergo some pre-processing before they are served. In production, Rails precompiles these files to public/assets by default. The precompiled copies are then served as static assets by the web server. The files in app/assets are never served directly in production.

How do I add a SCSS file to Rails?

You can just add the import to the application. scss file so it will look like: @import "bootstrap/bootstrap.

How do you Precompile an asset?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

What is Require_self?

//= require_self. It loads the file itself, to define the order that the files are loaded. Follow this answer to receive notifications.


2 Answers

This is how i solved the styling issue: (excuse the Haml)

%div{:id => "#{params[:controller].parameterize} #{params[:view]}"}     = yield 

This way i start all the page specific .css.sass files with:

#post   /* Controller specific code here */   &#index     /* View specific code here */   &#new   &#edit   &#show 

This way you can easily avoid any clashes.

Hope this helped some.

like image 131
zeeraw Avatar answered Sep 30 '22 18:09

zeeraw


I have a post about this on my website: Leveraging Rails 3.1, SCSS, and the assets pipeline to differentiate your stylesheets

And check out this answer to another question: Using Rails 3.1 assets pipeline to conditionally use certain css

Hope this helps.

Best regards, Lasse

like image 31
Lasse Bunk Avatar answered Sep 30 '22 17:09

Lasse Bunk