Help: ranging over menu items only adding active class to home page

In the <nav> of the site I’m working on the menu is generated by Hugo.
I definite it in the config.toml file. This is what it looks like:

[menu]
  [[menu.main]]
    name          = "Home"
    url           = "/"
    weight        = 1

  [[menu.main]]
    name          = "About"
    url           = "/about"
    weight        = 2

  [[menu.main]]
    name          = "Posts"
    url           = "/post"
    weight        = 3

Now in the <nav> I range over the menu to add each item, and for the active page the font-bold class gets added. This is what that looks like:

<ul class="menu md:float-right list-reset m-0 overflow-hidden p-0">
  {{- range .Site.Menus.main }}
  <li class="border-t md:float-left">
    <a class="block no-underline hover:text-indigo{{ if or ($.IsMenuCurrent "main" .) ($.HasMenuCurrent "main" .) }} font-bold{{ end }}" href="{{ .URL }}">{{ .Name }}</a>
  </li>
  {{- end }}
</ul>

When I am on the “Home” page, the font-bold class gets applied like it is supposed to, but not for any of the other menu items.

What am I doing wrong?

Try adding a trailing slash on each URL in the config?
e.g url = "/about/"

OK that helps. Now the font-bold class gets added to Posts section of the menu, but it still doesn’t get added to About
:thinking:

About is a single template page, originally I had it as /content/about.md but have also tried /content/about/index.md neither seems to make a difference.

:thinking:

Your code is actually the same as I’ve used on a project. The only other differences I can spot apart from the slash are -

  • I don’t have any dashes in the template statements {{- …}
  • I have {{ $currentPage := . }} declared right above {{ range .Site.Menus.main }}, but that’s for something else in the menu

I use /content/blah/_index.md for each section page as they’re branch and not leaf bundles but it sounds like using index.md works for you because it’s meant to be static https://gohugo.io/content-management/page-bundles/ ?

I managed to get the font-bold class applied the About page by taking the menus out of the config.toml file, and moving them into the frontmatter of each section.

menu = "main"
weight = 2

It’s not ideal, but it works. Would still love to know why it wasn’t working before.
The repo can be found here if anyone feels like looking for themselves.

1 Like