问题
Possible Duplicate:
Append class if condition is true in Haml (with Rails)
I'm using a template that allows you to mark a list item as current (using class=current), highlighting it in a nav bar.
In HAML, this looks like:
%li.current
Menu item A
%li
Menu item B
%li
Menu item C
I have this code in a Sinatra view and want to programmatically add the class=current, depending on a parameter to the view.
How do I do this in the neatest way possible?
Currently, I'm doing it like this:
- if section == "pages"
%li.current
%a{:href => "#pages"} Pages
- else
%li
%a{:href => "#pages"} Pages
Which feels too verbose.
回答1:
You can inline the conditional to determine if the class is needed for the %li
%li{ :class => ('current' if section == "pages") }
%a{ :href => "#pages" } Pages
回答2:
If section can be another string rather than "pages", you should use something like mguymon answered. But if it can only be nil, false or "pages" this code is more succinct:
%li{ class:section && 'current' }
%a{ :href => "#pages" } Pages
This use the principle that HAML omit nil or false attributes and every object in Ruby is evalueted as true, except: false and nil.
So, if section is different than nil or false, then section && 'current' outputs 'current' else it outputs false omitting the class attribute.
来源:https://stackoverflow.com/questions/12312052/neat-way-to-conditionally-test-whether-to-add-a-class-in-haml-template