简体   繁体   中英

Load different CSS in application layout based on page type (Ruby on Rails)

My application has pages of two basic types: forms and tables.

As such, I have two different CSS files, forms.css and tables.css.

In my application layout file (application.html.erb), I'd like to load different stylesheets depending on some sort of flag set in a given view.

For example, <%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %> <%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %> .

The above snippet doesn't actually work, but that's what I'm trying to accomplish?

Any ideas?

You should move this to a before_filter in your controller. Keep the view lightweight.

In the view:

<%=stylesheet_link_tag @foo %>

before_filter in Controller:

before_filter :get_css_file

def get_css_file
  @foo = defined?(@tables) ? 'tables' : 'forms'
end

I presume you set @tables in your controller, so you might have to adjust your logic, but you get the idea. In fact you already know if it's a table or form page controller, probably, so you'd basically just be setting @foo directly: @foo = 'tables' etc.

I've just tried a similar thing and it works for me. Your code isn't quite right, perhaps you just need to change it to

<%= stylesheet_link_tag(defined?(@tables) ? 'tables' : 'forms') %>

Your ternary operator syntax is wrong, if that's what you're trying to do. I think you mean this:

<%= defined?(@tables) ? stylesheet_link_tag 'tables' : stylesheet_link_tag 'forms' %>

The question mark (?) and colon (:) changed places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM