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.

+3


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!

+2


source


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

application_helper.rb

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

      



view

%body{ :class => get_class action_name }

      

+3


source


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

      

+1


source







All Articles