How to highlight Active Nav Menu in Hugo

After applying the Editorial theme to my website, I found that the menu item for the current page is not being highlighted. With some fiddling I was finally able to implement it with Go logic.

If you want to implement this for your theme/website, locate the code that actually renders the site menus. In the Editorial theme, it was present in layouts/partials/nav.html file (please note this might vary for different themes, just search for .Site.Menus.main in your theme files and you should be able to easily locate it).

In the below code snippet notice the lines highlighted (5, 9 and 20). In line #5, I am splitting the URL (eg. to get the page name (eg. post, projects, contactme, etc.). Once I have the page name, I am applying active class to the <li> element if the current menu (returned by a nice inbuilt $.IsMenuCurrent page method provided by hugo) object returns the same current page object. active class then highlights the menu for the current page.

There you have it. A simple Go template implementation to solve the current page tab highlighting issue.


{{ $currentNode := . }}

<!-- apply active class to the current tab -->
{{- $firstUrlElement := print "/" (index (split .URL "/") 1) -}}
{{ range .Site.Menus.main }}
    {{ if .HasChildren }}
    <li class="sub-menu{{if $currentNode.HasMenuCurrent "main" . }} active {{end}}">
        <span class="opener">{{ .Name }}</span>
        {{ range .Children }}
        <li><a href="{{ .URL }}">{{ .Name }}</a></li>
        {{ end }}
    {{ else }}
        <a href="{{ .URL }}" 
            class="{{if or ($.IsMenuCurrent "main" .) (in (.URL|lower) ($firstUrlElement|lower))}}active{{end}}">
            {{ .Name }}
    {{ end }}
{{ end }}

Recent Posts

← Go Back