Created
September 30, 2023 00:11
-
-
Save saiqulhaq/a247ce8d9230d0ea1ef7b337c6425619 to your computer and use it in GitHub Desktop.
Rails active_link_to helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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