Rails scss stylesheet per action

大兔子大兔子 提交于 2019-12-12 02:23:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!