如果Haml中的条件为真,则追加类

如果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。 Haml特有的,但仍然不简单:

 %div{:class => "post" + (" gray" unless post.published?).to_s} / Post stuff 
 .post{:class => ("gray" unless post.published?)} 
 - 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 

真的最好的事情是把它放进一个帮手。

 %div{ :class => published_class(post) } #some_helper.rb def published_class(post) "post #{post.published? ? '' : 'gray'}" end 

HAML有一个很好的方法来处理这个问题:

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

这样做的方式是条件获取评估,如果为true,则将string包含在类中,否则将不包含该string。