How to highlight a current link in a navbar? algorithm

Here’s how I did it in my project.

First, define a function in layout_view.ex,

  @doc """
  Set css class for active link.
  """
  @spec css_class(Plug.Conn.t(), String.t(), String.t(), String.t()) :: String.t()
  def css_class(conn, path, defaultClass, activeClass \\ "active") do
    if path == Phoenix.Controller.current_path(conn) do
      defaultClass <> " " <> activeClass
    else
      defaultClass
    end
  end

Then in my app.html.eex call the function:

<%= link "Dashboard", to: Routes.user_path(@conn, :show, @current_user), class: css_class(@conn, Routes.user_path(@conn, :show, @current_user), "nav-link") %>
6 Likes