Template variable not defined

I found a web site documenting how to create a menu with submenus and I copied the nav.html file from that site. There’s an error in nav.html. The file:

<nav class="nav">
    <ul class="menu">
        {{ range .Site.Menus.main }}
        <li class="{{ if $currentPage.HasMenuCurrent "main" . }}active{{ end }}">
            <span>{{ .Name }}</span>
            {{ if .HasChildren }}
            <span class="drop-icon" for="{{ .Name }}">▾</span>
            <ul class="sub-menu">
                {{ range .Children }}
                <li class="{{ if $currentPage.HasMenuCurrent "main" . }}active{{ end }}">
                    <span>{{ .Name }}</span>
                </li>
                {{ end }}
            </ul>
           {{ end }}
        </li>
        {{ end }}
    </ul>
</nav>

This throws an error when I try to invoke hugo server:

$ hugo server
Error: add site dependencies: load resources: loading templates:
"../layouts/partials/nav.html:4:1":
parse failed: template: partials/nav.html:4: undefined variable
"$currentPage"

Where do I define $currentPage so Hugo accepts the variable?

Look at the first example on this page:
https://gohugo.io/templates/menu-templates/

Joe,

I’ve started reading all the Hugo template pages and hadn’t yet come to the
menu page. This looks like it puts the menu on a sidebar rather than the top
of each page, but it’s a good start for me.

Thanks,

Rich

The point of that example is to show where $currentPage is initialized.

Try this

<nav class="nav">
    <ul class="menu">
      {{ $currentPage := . }}
        {{ range .Site.Menus.main }}
        <li class="{{ if $currentPage.HasMenuCurrent "main" . }}active{{ end }}">
            <span>{{ .Name }}</span>
            {{ if .HasChildren }}
            <span class="drop-icon" for="{{ .Name }}">▾</span>
            <ul class="sub-menu">
                {{ range .Children }}
                <li class="{{ if $currentPage.HasMenuCurrent "main" . }}active{{ end }}">
                    <span>{{ .Name }}</span>
                </li>
                {{ end }}
            </ul>
           {{ end }}
        </li>
        {{ end }}
    </ul>
</nav>

Tut,

Thank you very much. Another valuable lesson for a new Hugo user.

Much appreciated,

Rich

Thanks, Joe.

What threw me off is that the initialization was not included in the
source’s web page.

Regards,

Rich