16

I have this html

  <tr <% if ap.overdue? %>class = "overdue"<% end %> >
    <td><%= ap.id %></td>
    <td><%= link_to ap.affiliate.title, superadmin_affiliate_path(ap.affiliate) %></td>
  </tr>

How do I code the equivalent in HAML? In particular the first line, which assigns a class only if the if condition is true.

Marco Prins
  • 7,189
  • 11
  • 41
  • 76
  • 1
    http://html2haml.heroku.com/ you can use this website very helpful – matanco May 28 '14 at 10:47
  • 2
    Possible duplicate of [Append class if condition is true in Haml](https://stackoverflow.com/questions/3453560/append-class-if-condition-is-true-in-haml) – Ian Hunter Nov 14 '18 at 19:35

2 Answers2

30

Try this

%tr{ :class => ("overdue" if ap.overdue?) }
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • If you have classes that you always need and one or more variable classes, you can either use a variable (i.e. class: @some_var) or string interpolation with a ternary (i.e. class: "some-class #{ap.overdue? ? "overdue" : ""}") – Chris Hanson Nov 06 '14 at 16:59
4

HAML has a nice built in way to handle this:

%tr{ class: [ap.overdue? && 'overdue'] }

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