6

Possible Duplicate:
Append class if condition is true in Haml (with Rails)

I'm using a template that allows you to mark a list item as current (using class=current), highlighting it in a nav bar.

In HAML, this looks like:

%li.current
  Menu item A
%li
  Menu item B
%li
  Menu item C

I have this code in a Sinatra view and want to programmatically add the class=current, depending on a parameter to the view.

How do I do this in the neatest way possible?

Currently, I'm doing it like this:

  - if section == "pages"
    %li.current
      %a{:href => "#pages"} Pages
  - else
    %li
      %a{:href => "#pages"} Pages

Which feels too verbose.

Community
  • 1
  • 1
Daniel May
  • 2,192
  • 5
  • 25
  • 43

2 Answers2

18

You can inline the conditional to determine if the class is needed for the %li

%li{ :class => ('current' if section == "pages") }
  %a{ :href => "#pages" } Pages
mguymon
  • 8,946
  • 2
  • 39
  • 61
  • how can you use multiple Ifs for different classes per element with haml? – v3nt Feb 26 '14 at 11:24
  • Ideally you would not cram all the conditionals inline, it will be ugly and difficult to read. Instead, build the string of class names before and pass it into the haml tag. – mguymon Feb 26 '14 at 15:04
3

If section can be another string rather than "pages", you should use something like mguymon answered. But if it can only be nil, false or "pages" this code is more succinct:

%li{ class:section && 'current' }
  %a{ :href => "#pages" } Pages

This use the principle that HAML omit nil or false attributes and every object in Ruby is evalueted as true, except: false and nil.

So, if section is different than nil or false, then section && 'current' outputs 'current' else it outputs false omitting the class attribute.

Community
  • 1
  • 1
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64