Search code examples
ruby-on-railshaml

HAML class string with class based on if statement


I have this HAML code adding an "active" class based on an if statement.

= link_to 'Contact Information',
  edit_account_path(:contact_information),
  class: ("active" if params[:section] == 'contact_information')

I want to also add a string of classes permanently, outside of the if statement.

Something like

= link_to 'Contact Information',
  edit_account_path(:contact_information),
  class: "Tab large", ("active" if params[:section] == 'contact_information')

I need to do this without creating a helper method because I'm not allowed to edit the code too much.


Solution

  • Use the ternary operator:

    = link_to 'Contact Information',
      edit_account_path(:contact_information),
      class: "Tab large #{params[:section] == 'contact_information' ? 'active' : ''}"
    

    The second example:

    = link_to 'Contact Information',
      edit_account_path(:contact_information),
      class: current_page?(edit_user_registration_path) ? 'active' : ''