13

How to convert this ERB code:

<div <%= 'class="highlight"' if job.done %>>

into Haml code?

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Pewh Gosh
  • 1,031
  • 1
  • 11
  • 29

3 Answers3

17
%div{:class => ('hightlight' if job.done)}

I believe would also do the trick, and doesn't create class= '' if job.done == false, also looks more like your initial code

wvm2008
  • 2,864
  • 4
  • 21
  • 25
16
%div{class:job.done && "highlight"}

If you set an attribute to false or nil, Haml will omit the attribute altogether.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
-1
%div{job.done ? {:class => "highlight"} : {}}

%div{:class => job.done ? "highlight" : ""}
Victor Moroz
  • 9,167
  • 1
  • 19
  • 23
  • The latter actually creates `
    `, an empty class. This is functionally the same, but not the same output as requested by the OP.
    – Phrogz Jan 22 '12 at 04:40
  • @Phrogz Right, but in most cases it's ok. Your way is probably better, I didn't know it. – Victor Moroz Jan 22 '12 at 04:41