How to add a class to the current page in the menu item

How to add a class to the current page in the menu item
My menu is added through the site configuration:

[menus]
    [[menus.main]]
        name = 'a'
        pageRef = '/a'
        weight = 1
    [[menus.main]]
        name = 'b'
        pageRef = '/b'
        weight = 2
    [[menus.main]]
        name = 'c'
        pageRef = '/c'
        weight = 3

Template:

{{- range site.Menus.main }}
<li><a href="{{ .URL }}">{{ .Name }}</a></li>
{{- end }}

Tried an example but it didn’t work here: https://gohugo.io/methods/site/menus/

https://gohugo.io/content-management/menus/#params

https://gohugo.io/content-management/menus/#example

1 Like

Working solution only through front matter?

I don’t understand what cases the Menus method is for then?

{{ with site.Menus.main }}
  <nav class="menu">
    {{ range . }}
      {{ if $.IsMenuCurrent .Menu . }}
        <a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a>
      {{ else }}
        <a href="{{ .URL }}">{{ .Name }}</a>
      {{ end }}
    {{ end }}
  </nav>
{{ end }}

The code from the documentation should have worked for me.

I guess I don’t understand your objective.

I’m sorry.

I tried to use the code from the documentation:

{{ with site.Menus.main }}
  <nav class="menu">
    {{ range . }}
      {{ if $.IsMenuCurrent .Menu . }}
        <a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a>
      {{ else }}
        <a href="{{ .URL }}">{{ .Name }}</a>
      {{ end }}
    {{ end }}
  </nav>
{{ end }}

It didn’t work for me, and I started looking for other ways.

What are you trying to do?

I want for my menu: How to add a class to the current page in the menu item
Add

class=“active”

links if the page is the current page.

imho referencing your initial request won’t help. The implementation shown in the docs works pretty well,

So it looks like your use case is different from our common sense. And you should explain it in more detail.

if you play with the built-in Hugo theme, you can see that it has a menu of top level sections and classes are assigned to the pages:

  • on a main section or home page: the top level menu gets the class “active”
  • on a single page in a section (posts) : the section menu gets class “ancestor”
  • other entries get no class.

play with it - maybe that will help to provide details we are missing.

hugo new theme --themesDir menu-test
cd menu-test
hugo server

p.s. the tags pages are not handled. it may display pages from different top level sections. maybe that’s your case? I’m pretty sure this could be addressed.

1 Like