Skip to content

Instantly share code, notes, and snippets.

@saiqulhaq
Created September 30, 2023 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saiqulhaq/a247ce8d9230d0ea1ef7b337c6425619 to your computer and use it in GitHub Desktop.
Save saiqulhaq/a247ce8d9230d0ea1ef7b337c6425619 to your computer and use it in GitHub Desktop.
Rails active_link_to helper
module ApplicationHelper
def active_class(link_path)
current_path = request.path
# Special case for root path
return 'active' if current_path == '/' && link_path == '^/$'
return '' if current_path != '/' && link_path == '^/$'
# Use Regex to match the route or any conditions you need
current_path.match(Regexp.new(link_path)) ? 'active' : ''
end
end
<!-- app/views/layouts/application.html.erb -->
<nav>
<ul>
<li class="<%= active_class('^/$') %>">
<%= link_to 'Home', root_path %>
</li>
<li class="<%= active_class('^/about') %>">
<%= link_to 'About', about_path %>
</li>
<li class="<%= active_class('^/contact') %>">
<%= link_to 'Contact', contact_path %>
</li>
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment