When creating navigation templates for hugo, it is a common practice to generate a navigation item for each item in the menu. One of these will be highlighted by using the .IsMenuCurrent function on the current page to compare the current page with the page of the menu entry. This only works with pages with menu in the frontmatter.

Suppose you have a site layout like mine:

posts/
    _index.md (menu: main)
    post.md
projects/
    _index.md (menu: main)
    project.md
food/
    _index.md (menu: main)
    food.md

Any user that visits subpages like /posts/post or /food/food will not trigger the .IsMenuCurrent on the page, since these pages are not in the menu.

A solution is provided on the hugo forums. However, I do not think that it is portable to use string comparison to compare the menu title with the section title, or the section url with the page url.

Solution

There is a .Section variable that gives the string of the parent section for the current page. I can use .GetPage to turn this string into a page, then call .IsMenuCurrent on the section page.

{{ $currentPage := . }}
{{ $section := .Site.GetPage $currentPage.Section }}
{{ range .Site.Menus.main }}
<a class="navbar-item {{if $section.IsMenuCurrent "main" . }}is-active{{end}}" href="{{ .URL | absLangURL | safeURL }}">{{ .Name }}</a>
{{ end }}