开发者

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

开发者 https://www.devze.com 2023-04-10 12:41 出处:网络
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 som开发者_如何学JAVAe views?Like if I want admin.css.scss include

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 som开发者_如何学JAVAe views? Like if I want admin.css.scss included in the admin page and main.css.scss in the home/about/contact page.


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'


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.


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

(see sections 2.2.14 'Finding Layouts')

you could have different layouts for different controllers!

e.g. under app/views/layouts you could have application.haml and admin.haml and under app/controllers you'd have a admin_controller.rb

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

You can also override this behavior and specify which layout to use, e.g.:

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

You would then create an admin.scss file under app/stylesheets for this new layout!

0

精彩评论

暂无评论...
验证码 换一张
取 消