Rails3.1 - How to include css files in some views, but not others?

It seems that in rails 3.1 all css.scss files are merged into 1 file. What should I do if I want the css file to be included only in some views? For example, if I want admin.css.scss to be enabled on the admin page and main.css.scss on the home / about / contact page.

+8
ruby-on-rails-3 compass-sass
source share
3 answers

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

/* * 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 generally better to create a new file per style scope. *= require_self *= require_tree . */ 

This is due to * = require_tree.

For a stylesheet, you may need:

 *= require main 

Otherwise, in your layout you write:

 %head = yield :head 

and on your page:

 = content_for :head do = stylesheet_link_tag 'stylesheet' 
+13
source share

Let me add a solution that worked for me.

As mentioned in the previous answer, you can remove

  *= require_tree . 

from application.css file.

I saved

  *= require_self 

for general styles in the app.

Then, in my application.html file, I used the following operators to include only application.css and controller.controller_name.css stylesheets 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.

+10
source share

See also:
http://guides.rubyonrails.org/layouts_and_rendering.html

(see sections 2.2.14 "Searching for Layouts")

You may have different layouts for different controllers!

eg. in application / views / layouts you can have application.haml and admin.haml and for applications / controllers you will have admin_controller.rb

Rails will try to find the layout with the same name as the controller.

You can also override this behavior and specify which layout to use, for example:

 class ItemsController < ApplicationController layout "admin" #... end 

Then you will create an admin.scss file under the application / style sheets for this new layout!

+3
source share

All Articles