Hugo menu link to heading using id

I have a heading that’s halfway down on my homepage and I would like to link to this heading in my navbar menu. I tried adding it as a new menu entry in my toml file. I used pageRef=‘/#heading-id’ but it did not work.

Is it possible to add this heading to my menu somehow?

I have had a look at the Hugo docs page on menus but I couldn’t see how.

Site configuration

[[menus.main]]
name = 'Home (Section 2)'
pageRef = '/'
weight = 10
[menus.main.params]
fragment = 'section-2'

[[menus.main]]
name = 'Post 1 (Section 3)'
pageRef = '/posts/post-1'
weight = 20
[menus.main.params]
fragment = 'section-3'

Then the menu code would look something like this:

{{ with site.Menus.main }}
  <nav class="nav-inline menu">
    <ul>
      {{ range . }}
        {{ $href := .URL }}
        {{ with .Params.fragment }}
          {{ $href = printf "%s#%s" $href . }}
        {{ end }}
        {{ if $.IsMenuCurrent .Menu . }}
          <li class="active"><a aria-current="page" href="{{ $href }}">{{ .Name }}</a></li>
        {{ else if $.HasMenuCurrent .Menu . }}
          <li class="ancestor"><a aria-current="true" href="{{ $href }}">{{ .Name }}</a></li>
        {{ else }}
          <li><a href="{{ $href }}">{{ .Name }}</a></li>
        {{ end }}
      {{ end }}
    </ul>
  </nav>
{{ end }}

The above retains both the fragment and query string.

Thanks. Unfortunately I’m still a beginner with Hugo and I’m struggling with your partial above. I completely replaced my menu.html partial with your suggestion but I’m getting an error on the “range” line:

render: failed to render pages: range can’t iterate over [lists some memory addresses]

Don’t want to come across as lazy but I’m just wondering if anything comes to your mind, since I’m trying your suggestion.

Thanks again.

I’ve revised the code above to use the menu params key.

Try it:

git clone --single-branch -b hugo-forum-topic-53592 https://github.com/jmooring/hugo-testing hugo-forum-topic-53592
cd hugo-forum-topic-53592
hugo server

Then compare to what you have done.

I tried your edited partial and it’s working perfectly now. Thank you.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.