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:

1 Like

Figured I would put this information here for anyone who finds this in the future:

The method above didn’t quite work for my use case, which is a nav that only lists the top-level sections of the site. I ended up doing this:

{{ $currentPage := .Section }}
    {{ range .Site.Menus.main }}
        <li class="nav-item text-center">
            <a class="nav-link{{ if eq $currentPage .Page.Section }} active{{ end }}" href="{{ .URL }}">{{ .Title }}</a>
        </li>
{{ end }}

Haven’t tried putting an individual page on there (like an “about us” or something.) It might break in that case.