如果post.published?
.post
/ Post stuff
否则
.post.gray
/ Post stuff
我用rails helper实现了它,看起来很难看。
= content_tag :div, :class => "post" + (" gray" unless post.published?).to_s do
/ Post stuff
第二种变体:
= content_tag :div, :class => "post" + (post.published? ? "" : " gray") do
/ Post stuff
是否有更简单和特定于haml的方式?
UPD。 Haml特有的,但仍然不简单:
%div{:class => "post" + (" gray" unless post.published?).to_s}
/ Post stuff
答案 0 :(得分:315)
.post{:class => ("gray" unless post.published?)}
答案 1 :(得分:21)
- classes = ["post", ("gray" unless post.published?)]
= content_tag :div, class: classes do
/Post stuff
def post_tag post, &block
classes = ["post", ("gray" unless post.published?)]
content_tag :div, class: classes, &block
end
= post_tag post
/Post stuff
答案 2 :(得分:14)
最好的办法就是把它变成帮手。
%div{ :class => published_class(post) }
#some_helper.rb
def published_class(post)
"post #{post.published? ? '' : 'gray'}"
end
答案 3 :(得分:14)
HAML有一个很好的内置方法来处理这个问题:
.post{class: [!post.published? && "gray"] }
这种方法的工作方式是条件得到评估,如果是,则字符串包含在类中,否则不会包括在内。
答案 4 :(得分:2)
更新的Ruby语法:
.post{class: ("gray" unless post.published?)}