Save html to variable of double menu to improve performance of big site 40k pages

Hello, I have a website with 40k pages. The site has two menus. one for mobile and one for desktop. each menu is generated in its own partial with the bellow same code on both partials:

{{ $type := .Type }}
{{ $kind := .Kind }}
{{ $currentPage := . }}
{{ range .Site.Menus.main }}
  <li class="menu-item {{ if or ($currentPage.IsMenuCurrent "main" .) ($currentPage.HasMenuCurrent "main" .) }} is-active{{ end }}{{ if and (eq .Identifier "home") (eq $type "post") }} is-active{{ end }}{{ if and (eq .Identifier "home") (and (eq $type "page") (eq $kind "taxonomy"))}} is-active{{ end }}">
    <a href="{{ .URL }}">{{ .Name }}</a>
  </li>
{{ end }}

Is there any way to save this in a variable and then pass it to each partial Or any other workaround to prevent the generation of exact same menu 2 times.

Have you tried the partialCached template function? https://gohugo.io/functions/partialcached/#readout

I tried but it does not work because I want to add a class on active menu.

Check out the “variants” feature of partialCached. Or I would call it cache tags and not variants.

You would need to use the same partial for both menus and add the current page as the variant. I think that would make the second invocation use the cache.

2 Likes

What triggers the active state?

Is it the page belonging to a section? Then you can use .Section as a variant. If there is another factor the you can add or as well.

partialCached takes any number of variant arguments as long as their type is string.

{{ $isHome := cond .IsHome “home” “nohome” }}
{{ partialCached “menu.html” . .Section $isHome }}
2 Likes

Eventually I did it with javascript and cache completely the partial

(function () {
    var current = location.pathname.split('/')[1];
    if (current === "") return;
    var menuItems = document.querySelectorAll('.menu-item a');
    for (var i = 0, len = menuItems.length; i < len; i++) {
        if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
            menuItems[i].className = "is-active";
        }
    }
})();