sara lance
sara lance

Reputation: 603

Changing an element styles given a string pattern in Rails

What to change give an active class to a li depending of the route.

I have this routes:

/profile/2

/profile/2/info

/profile/2/contact

I have a menu

<ul>
 <li>
   <%= link_to 'Profile', profile_path(current_user), class: current_class_contains?('/profiles') %>
 </li>
 <li>
   <%= link_to 'Info', info_profile_path(current_user), class: current_class_contains?('/info') %>
 </li>
 <li>
   <%= link_to 'Contact', contact_profile_path(current_user), class: current_class_contains?('/contact') %>
 </li>
</ul>

In application_helper

module ApplicationHelper
  def current_class_contains?(test_path)
    return "active" if request.path.match(test_path)
    ""
  end

  def current_class?(test_path)
    return "active" if request.path == test_path
    ""
  end
end

The problem that I got is that if I'm in /profile/2/info or /profile/2/contact the Profile li is also given the active class.

I can't figure it out. Any ideas?

Upvotes: 0

Views: 62

Answers (2)

spickermann
spickermann

Reputation: 107037

I would use current_page? to build a helper method like this:

def indicating_link_to(name, url)
  css_class = 'active' if current_page?(url)
  link_to(name, url, class: css_class)
end

And use that helper method like this in your view:

<ul>
  <li>
    <%= indicating_link_to 'Profile', profile_path(current_user) %>
  </li>
  <li>
    <%= indicating_link_to 'Info', info_profile_path(current_user) %>
  </li>
  <li>
    <%= indicating_link_to 'Contact', contact_profile_path(current_user) %>
  </li>
</ul>

And with the new class_names method that will be introduced with Ruby on Rails 6.1 it will be even simpler:

def indicating_link_to(name, url)
  link_to(name, url, class: class_names(active: current_page?(url)))
end

Upvotes: 1

Salil
Salil

Reputation: 47522

Use current_page?, Something like following

return "active" if current_page? test_path

& calling

current_class_contains?(profile_path(current_user))

Upvotes: 1

Related Questions