Frontier Software

Menus

Directory traversal

I’ve developed my own homegrown way of recursively walking a Hugo site’s content tree as described in this discourse thread since the official way of putting the menu in the site config file isn’t what I want as I add and remove pages.

With more experience, I changed the deprecated template with an inline partial

My code for layouts/partials/menu.html looks like this:

<nav>
{{ partial "inline/walk.html" (dict "dir" .Site.Home.Pages) }}

{{ define "partials/inline/walk.html" }}
  <ol>
  {{ range .dir }}
    {{ if (eq .BundleType "branch") }}
        <li><a href="{{ .RelPermalink }}">{{ .Title }}</a>
        {{ partial "inline/walk.html" (dict "dir" .Pages) }}
        </li>
    {{ else }}
      <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
    {{ end }}
  {{ end }}
  </ol>
{{ end }}
</nav>

Section menu

Hugo’s default menu system requires everything to be manually entered into the system configuration file.

To only list first-secions, in site config, add

{
  "sectionPagesMenu": "main",
}

Note “main” is just an example name, it can be anything. The top most menu entries can then be accessed by site.Menus.main.

<nav>
 <ul>
  {{ range .Site.Menus.main }}
   <li><a href="{{ .URL }}">{{ .Name }}</a></li>
  {{ end }}
 </ul>
</nav>

Subsections

This seems very clunky to me, involving editing the site configuration file to include every subsection wanted in the menu:

  "menus": {
    "main": [
      {
        "name": "bash",
        "pageRef": "/bash"
      },
      {
        "name": "coreutils",
        "pageRef": "/bash/coreutils",
        "parent": "bash" 
      },
      {
        "name": "util-linux",
        "pageRef": "/bash/util-linux",
        "parent": "bash" 
      },
      {
        "name": "hugo",
        "pageRef": "/hugo"
      }
    ]
  },

The example for MENUENTRY.HasChildren isn’t recursive.

<ul>
  {{ range .Site.Menus.main }}
    <li>
      <a href="{{ .URL }}">{{ .Name }}</a>
      {{ if .HasChildren }}
        <ul>
          {{ range .Children }}
            <li><a href="{{ .URL }}">{{ .Name }}</a></li>
          {{ end }}
        </ul>
      {{ end }}
    </li>
  {{ end }}
</ul>