Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3.1 - How do I include css files in some views but not others?

It seems that, in rails 3.1, all of the css.scss files get merged into 1 file. What do I do if I want a css file to only be included in some views? Like if I want admin.css.scss included in the admin page and main.css.scss in the home/about/contact page.

like image 665
NotDan Avatar asked Oct 05 '11 01:10

NotDan


2 Answers

In Rails 3.1, all your stylesheets will be merged into the application.css if your application.css looks like:

/*
 * This is a manifest file that'll automatically include all the stylesheets available in this directory
 * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
 * the top of the compiled file, but it's generally better to create a new file per style scope.
 *= require_self
 *= require_tree . 
*/

It's due to the *=require_tree .

You can require a specific stylesheet with:

*= require main

Otherwise, in your layout, you write:

%head
 = yield :head

and in your page:

= content_for :head do
 = stylesheet_link_tag 'stylesheet'
like image 99
damienbrz Avatar answered Sep 28 '22 02:09

damienbrz


Let me add a solution that worked for me.

As mentioned in a previous answer you might want to remove the

 *= require_tree . 

statement from the application.css file.

I kept the

 *= require_self

statement for shared styles across the application.

Then in my application.html file I used the following statements to include only the application.css and the controller.controller_name.css style sheets in the view.

= stylesheet_link_tag "application", controller.controller_name
= javascript_include_tag "application", controller.controller_name

As you can see the same works for JavaScript files.

like image 22
Ely Avatar answered Sep 28 '22 02:09

Ely