Mark menu item with an active child in a recursive menu

Hi guys!

This took me some time: I wanted to find out whether a menu item has an active child.

I hope someone can profit from my solution because this question has come up several times here.

This solution works with multilingual menus, too. Just replace relURL with relLangURL.

If you have a more elegant solution feel free to post it below.

config.yml

menu:
  main:
    - name: Start
      url: /
      identifier: start
      weight: 1
    - name: Subment Item 1
      url: /sub-1/
      parent: start
      weight: 1.1
    - name: Subment Item 2
      url: /sub-2/
      parent: start
      weight: 1.2
    - name: Blog
      url: /blog/
      weight: 2

_baseof.html

{{ partial "menu.html" (dict "menu" .Site.Menus.main "currentPage" . "section" .Section) }}

menu.html

{{ $parent := "" }}

<ul>
  {{ range .menu }}
    {{ $current := eq $.currentPage.RelPermalink (.URL | relURL) }}
    {{ $current = or $current (eq $.section (lower .Name)) }}

    {{ if .HasChildren }}

      {{ range .Children }}
        {{ if eq $.currentPage.RelPermalink (.URL | relURL) }}
          {{ $parent = .Parent }}
        {{ end }}
      {{ end }}

      <li {{ if eq .Identifier $parent }} class="has-current-child"{{ end }}>
        <a href="{{ .URL | relURL }}" {{ if $current }} class="current"{{ end }}>{{ .Name }}</a>
          {{ partial "menu-recursive.html" (dict "menu" .Children "currentPage" $.currentPage) }}
      </li>

    {{ else }}

      <li>
        <a href="{{ .URL | relURL }}"{{ if $current }} class="current"{{ end }}>{{ .Name }}</a>
      </li>

    {{ end }}

  {{ end }}
</ul>
1 Like