HUGO

How to set navigation class on current page

currently I am trying to add a extra bootstrap class to my a tags when the current page is active. by default the class should be nav-link and when the current page is active the class should be nav-link active.

the code below shows the current setup for my navigation, if anyone knows how to achieve this please let me know.

  {{ $currentPage := . -}}
  {{ range .Site.Menus.main -}}

    <li class="nav-item">
      <a class="nav-link" href="{{ .URL | relLangURL }}" {{ if or ($currentPage.IsMenuCurrent "main" .) ($currentPage.HasMenuCurrent "main" .) }} class="nav-link active" aria-current="page" {{ end }}>{{ .Name }}</a>
    </li>
    {{ end -}}
{{ if eq $currentPage . }} class="nav-link active" aria-current="page" {{ end }}

So full code is:

{{ $currentPage := . -}}
{{ range .Site.Menus.main -}}
  <li class="nav-item">
      <a class="nav-link" href="{{ .URL | relLangURL }}" {{ if eq $currentPage . }} class="nav-link active" aria-current="page" {{ end }}>{{ .Name }}</a>
  </li>
{{ end -}}
1 Like

Just a side note: This works only on one-dimensional menus. If you have a submenu it gets more complicated, but Hugo has variables like .IsParent and .IsAncestor to work through this:

CSS does not (yet fully) support making the parent menu item active if a subitem has a certain class. Waiting for this one :slight_smile:

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

1 Like