How do I use an if statement in HAML to manipulate a tag class string?

I have a condition where if action_name contains "index" then the second class should only return "index", otherwise set it to action_name.

I tried something like this:

  - if action_name =~ /.*index.*/
    %body{ :class => "#{controller_name} index" }
  - else
    %body{ :class => "#{controller_name} #{action_name}" }


Unfortunately, I left the rest of my body in the layout that follows them and it shows up for suggestion only else


I suppose there is a more readable one liner I could use here, and also if it was doing an if inside a line versus a more verbose multi-line if statement, but I could use some help here to get that to work as expected in HAML.


source to share

3 answers

Well, here's one liner:

%body{ :class => "#{controller_name} #{(action_name =~ /.*index.*/) ? 'index' : action_name}" }


Not that much to read though!



I would put the method in a helper. I like to keep logic out of my views.


def get_class(name)
  "#{controller_name} #{(name =~ /.*index.*/) ? 'index' : name}"



%body{ :class => get_class action_name }




%body{:class => "#{controller_name} #{(action_name =~ /[index]/) ? 'index' : action_name}" }




All Articles