Haml: If statement inside attribute declaration

耗尽温柔 提交于 2020-01-06 19:40:48

问题


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

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