160

If post.published?

.post
  / Post stuff

Otherwise

.post.gray
  / Post stuff

I've implemented this with rails helper and it seems ugly.

= content_tag :div, :class => "post" + (" gray" unless post.published?).to_s do
  / Post stuff

Second variant:

= content_tag :div, :class => "post" + (post.published? ? "" : " gray") do
  / Post stuff

Is there a more simple and haml-specific way?

UPD. Haml-specific, but still not simple:

%div{:class => "post" + (" gray" unless post.published?).to_s}
  / Post stuff
Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74

5 Answers5

336
.post{:class => ("gray" unless post.published?)}
Nathan Weizenbaum
  • 3,376
  • 1
  • 15
  • 2
22
- 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
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
15

Really the best thing is to put it into a helper.

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

#some_helper.rb

def published_class(post)
  "post #{post.published? ? '' : 'gray'}"
end
mark
  • 10,316
  • 6
  • 37
  • 58
  • I've put this in my helper file, but my app tells me, that there is no "post" variable. – Simon Perepelitsa Aug 10 '10 at 22:16
  • 2
    fyi: if you only want to include a class in a certain case and nothing in other cases you can just set `nil` and the attribute will not be set, instead of setting `class=""` – MMachinegun Aug 07 '14 at 10:45
14

HAML has a nice built in way to handle this:

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

The way that this works is that the conditional gets evaluated and if true, the string gets included in the classes, if not it won't be included.

Jared
  • 2,408
  • 2
  • 19
  • 33
6

Updated Ruby syntax:

.post{class: ("gray" unless post.published?)}
Drew Haines
  • 61
  • 1
  • 3