Ruby on Rails: Highlight link_to current_page
Often to improve your navigation UI (user experience), you will want to mark the link to current page “active”:
the simple way to do it (assuming a bootstrap navbar):
<li class="<%= 'active fw-bold' if current_page?(root_path) %> nav-item">
<%= link_to "Homepage", root_path, class: 'nav-link' %>
</li>
or if you want to add some fancy fontawesome:
<li class="<%= 'active fw-bold' if current_page?(root_path) %> nav-item">
<%= link_to root_path, class: 'nav-link' do %>
<i class="fa fa-home"></i>
Homepage
<% end %>
</li>
however when you have a lot of links, your code will look “dirty”.
To make it look cleaner, you can add the following lines to application_helper.rb
:
def active_link_to(name, path)
content_tag(:li, class: "#{'active fw-bold' if current_page?(path)} nav-item") do
link_to name, path, class: "nav-link"
end
end
end
def deep_active_link_to(path)
content_tag(:li, class: "#{'active fw-bold' if current_page?(path)} nav-item") do
link_to path, class: "nav-link" do
yield
end
end
end
def deep_active_link_to_dropdown_item(path)
content_tag(:li) do
link_to path, class: "#{'active fw-bold' if current_page?(path)} dropdown-item" do
yield
end
end
end
this way you can write links like this
<%= active_link_to "homepage" root_path %>
or
<%= deep_active_link_to root_path do %>
<i class="fa fa-home"></i>
Homepage
<% end %>