如果条件在 Haml 为真,则附加 class

如果 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

有没有更简单,更专业的方法?

UPD 哈姆尔特有,但还不简单:

%div{:class => "post" + (" gray" unless post.published?).to_s}
/ Post stuff
73160 次浏览

其实最好的办法就是把它放进一个帮手里。

%div{ :class => published_class(post) }


#some_helper.rb


def published_class(post)
"post #{post.published? ? '' : 'gray'}"
end
- 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
.post{:class => ("gray" unless post.published?)}

HAML 有一个很好的内置方式来处理这个问题:

.post{class: [!post.published? && "gray"] }

这种方法的工作原理是对条件进行求值,如果为 true,字符串将包含在类中,否则不包含它。

更新的 Ruby 语法:

.post{class: ("gray" unless post.published?)}