We already range through the menu, why do both arguments need to mention the menu name again instead of relying on the dot for context?
That’s a good question. Each menu entry has a .Menu method, so it knows to which menu object it belongs. These two are, as far as I can tell, equivalent:
{{ $currentPage := . }}
{{ range site.Menus.main }}
{{ $currentPage.IsMenuCurrent .Menu . }} --> returns true/false
{{ end }}
{{ $currentPage := . }}
{{ range site.Menus.main }}
{{ $currentPage.Eq .Page }} --> returns true/false
{{ end }}
This is brilliant! I have been doing it like below requiring mentioning the menu again, hence my question (and again the versatility of Hugo)
{{ $currentPage := . }}
{{ range site.Menus.main }}
{{ $currentPage.IsMenuCurrent "main" . }}
{{ end }}
Yeah, definitely cleaner. This is used in both the example in the documentation, and in the partial when creating a skeleton theme (e.g., hugo new theme foo or hugo new theme foo --themesDir .).
I adopted this in my menu recently though the Issue I had is it required duplicating the Tailwind classes I used for the dict part since the styles were not applied in the three states (see below).
{{- define "partials/inline/menu/walk.html" }}
{{- $page := .page }}
{{- range .menuEntries }}
{{- $attrs := dict "href" .URL }}
{{- if $page.IsMenuCurrent .Menu . }}
{{- $attrs = merge $attrs (dict "class" "text-md bg-blue-450 dark:bg-blue-650 relative block cursor-pointer font-bold text-white md:border-r md:border-r-white/[.1] md:px-5" "aria-current" (i18n "aria-current")) }}
{{- else if $page.HasMenuCurrent .Menu .}}
{{- $attrs = merge $attrs (dict "class" "text-md bg-blue-450 dark:bg-blue-650 relative block cursor-pointer font-bold text-white md:border-r md:border-r-white/[.1] md:px-5" "aria-current" "true") }}
{{- else }}
{{- $attrs = merge $attrs (dict "class" "text-md hover:bg-blue-450 relative block cursor-pointer font-bold text-slate-200 transition-all delay-0 duration-300 ease-out hover:text-white dark:text-slate-300 md:border-r md:border-r-white/[.1] md:px-5") }}
{{- end }}
Use a var instead of string for the duplicated classes.
Awesome! I added the else part to style the menu in its default state. Otherwise only the other two were styled. Adding the styles to the anchor element overrides the dict values.