Highlight category menu when post is open

How do I do this? I want the category menu item to be active when a post in that category is opened.

config/_default/menus.toml

[[main]]
name = 'Home'
pageref = '/'
weight = 1

[[main]]
name = 'About'
pageref = '/about'
weight = 2

[[main]]
name = 'Contact'
pageref = '/contact'
weight = 3

[[main]]
name = 'Category A'
pageref = '/categories/category-a'

[[main]]
name = 'Category B'
pageref = '/categories/category-b'

[[main]]
name = 'Category C'
pageref = '/categories/category-c'

template

<ul>
  {{ $currentPage := . }}
  {{ range site.Menus.main }}
    {{ if $currentPage.IsMenuCurrent "main" . }}
      <li class="active">
        <a href="{{ .URL }}">{{ .Name }} (active a)</a>
      </li>
    {{ else if and (not .Page.IsHome) (in .Page.Pages $currentPage) }}
      <li class="active">
        <a href="{{ .URL }}">{{ .Name }} (active b)</a>
      </li>
    {{ else }}
      <li>
        <a href="{{ .URL }}">{{ .Name }}</a>
      </li>
    {{ end }}
  {{ end }}
</ul>

This is a crude example, marking a menu item “active a” if the current page matches the menu entry, or marking the menu item “active b” if the current page is a child page of the page represented by the menu item.

Note that all of the menu entries have the pageref property. If you include an external link in your menu using the url property, the template code will fail due to a nil pointer… defend accordingly.

It worked! Thanks. I needed this part

{{ else if and (not .Page.IsHome) (in .Page.Pages $currentPage) }}
      <li class="active">
        <a href="{{ .URL }}">{{ .Name }} </a>
      </li>

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