问题
How can I render a stylesheet per action in rails?
Since my app is not the standart CRUD app, my controllers end up with a few custom routes which require very different CSS's.
So, I'm wondering, is there any way to load the css on a per action basis but still take advantage of the asset pipeline?
Thanks
回答1:
create a directory for each of your controllers inside stylesheets directory and create css files corresponding to your action, then put this in you layout file
<%= stylesheet_link_tag "#{params[:controller]}/#{params[:action]}" %>
回答2:
You can use controller specific assets. Just remove the *= require_tree .
from application.css. And include the stylesheet the action specific stylesheet in its view by <%= stylesheet_link_tag "style.css" %>
but you have to tell rails to compile them by Rails.application.config.assets.precompile = ["style.css"]
. You can read more about it here. This way I guess we are using rails assets pipelines just not in default way.
回答3:
Add a unique id to the body based on the controller path and action:
Helper:
def page_id
"#{controller_path.tr('/', '-')}-#{action_name}".dasherize
end
Layout:
<body id="<%= page_id %>"...
Then scope your styles to it:
/users/index.scss
#users-index {
.. page specific styles here ..
}
来源:https://stackoverflow.com/questions/34022991/rails-scss-stylesheet-per-action