问题
I'm trying to put a conditional for a style attribute. According to this answer something like this should be possible:
.hello{:style => (true ? 'color: green' : 'color: red;')}
But for me the style attribute doesn't get outputted at all. Did things change in Haml? I rather not create a helper for such simple logic.
回答1:
I would take the easy route out and add a line:
- color = true ? 'color: green' : 'color: red;'
.hello{:style => color}
The even easier way is to add a further class and control it from the css/javascript as needs be:
- success_class = true ? 'success' : 'failed'
.hello{:class => success_class}
This would give you <div class='hello success'></div>
Edit: the ternary seems to work too, though
require 'haml'
# => true
str = ".hello{:class => true ? 'green' : 'red' }"
# => ".hello{:class => true ? 'green' : 'red' }"
Haml::Engine.new(str).render
# => "<div class='green hello'></div>\n"
str = ".hello{:style => true ? 'color:green' : 'color:red' }"
# => ".hello{:style => true ? 'color:green' : 'color:red' }"
Haml::Engine.new(str).render
# => "<div class='hello' style='color:green'></div>\n"
来源:https://stackoverflow.com/questions/34446554/haml-if-statement-inside-attribute-declaration