DEV Community

Cover image for Highlight link to current page: TLDR
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Edited on • Originally published at blog.corsego.com

2 2

Highlight link to current page: TLDR

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 font-weight-bold' if current_page?(root_path) %> nav-item">
  <%= link_to "Homepage", root_path, class: 'nav-link' %>   
</li>
Enter fullscreen mode Exit fullscreen mode

or if you want to add some fancy fontawesome:

<li class="<%= 'active font-weight-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>
Enter fullscreen mode Exit fullscreen mode

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 font-weight-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 font-weight-bold' if current_page?(path)} nav-item") do
    link_to path, class: "nav-link" do
      yield
    end
  end 
end 
Enter fullscreen mode Exit fullscreen mode

this way you can write links like this

<%= active_link_to "homepage" root_path %>
Enter fullscreen mode Exit fullscreen mode

or

<%= deep_active_link_to root_path do %>
  <i class="fa fa-home"></i>
  Homepage 
<% end %>
Enter fullscreen mode Exit fullscreen mode

That's it!🤠

Liked this article? Please follow me! It will really motivate me to post more fun stuff!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs