Haml: If statement inside attribute declaration

2019-09-16 15:40发布

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条回答
冷血范
2楼-- · 2019-09-16 16:23

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"
查看更多
登录 后发表回答