Hugo

Auto-generate links to pages in same directory?

I am attempting to document certain Things. Each Thing has a directory (content/things/thing-1) and there are several pages, in this directory, that are all very closely related and navigation between them should be simple.

For example:

  • index.md (overview over thing-1)
  • material.md (the material that thing-1 is made of)
  • size.md (the size of thing-1)
  • order.md (how to order thing-1)

I’m looking for something like a shortcode that:

  • collects all *.md files in content/things/thing-1/
  • reads the title in their front matter
  • and generates an HTML ul with an li for all other pages in the directory, using their title as the clickable text of a hyperlink.

Somehow I think I’m not the first guy to want this, but I’m a little lost how to this. This is what I have, and I’m not sure how I can go “back to the Hugo level” and use the page’s title and URL:

<ul>
  {{ range (readDir ( printf "/content/%s" .Page.Dir )) }}
    {{ if eq ".md" ( path.Ext .Name ) }}
      <li>{{ .Name }}</li>
    {{ end }}
  {{ end }}
</ul>

How do I best do this?

Something like this (french) example?

{{ $current := . }}
{{ with .Parent }}
{{ if ne .URL "/"}}
<aside>
  <h1>Voir aussi</h1>
  <ul>
    {{ range .Pages }}
    {{ if ne $current .}}
    <li>
      <a href="{{ .URL }}">{{ .Title }}</a>
    </li>
    {{ end }}
    {{ end }}
  </ul>
</aside>
{{ end }}
{{ end }}

Minimal version in your list template:

{{ with .Parent }}
  <ul>
    {{ range .Pages }}
    <li>
      <a href="{{ .URL }}">{{ .Title }}</a>
    </li>
    {{ end }}
  </ul>
{{ end }}
1 Like

The code above is great. I would just use not .IsHome as .URL is deprecated and a non-default language home would not be detected by this test.

2 Likes

Ah, very nice!