Can't make file tree properly

I’m trying to make a partial that displays the structure of content/docs as a clickable file tree. My content/docs directory looks like this:

  • _index.md
    • subdirectory1
      • _index.md
      • subsubdirectory1
        • _index.md
        • ss1p1.md
        • ss1p2.md
      • s1p1.md
    • subdirectory2
      • index.md
      • s2p1.md
    • subdirectory3
      • _index.md
      • s3p1.md
  • glossary

I’d like it to render like this:

  • Introduction
  • S1 Index
    • S1 Page 1
    • S1 Page 2
    • SS1 Index
      • SS1 Page 1
      • SS1 Page 2
  • S2 Index
    • S2 Page 1
    • S2 Page 2
  • S3 Index
    • S3 Page 1
    • S3 Page 2
  • Glossary

Here’s my current attempt:

<aside id="file-tree">
  <h3>File Tree</h3>
  <ul>
    {{ range (where .Site.Pages "Section" "docs") }}
      {{ if .IsSection }}
        <li>
          <a href="{{ .Permalink }}">{{ .Title }}</a>
          {{ if .Pages }}
            <ul>
              {{ range .Pages }}
                <li>
                  <a href="{{ .Permalink }}">{{ .Title }}</a>
                </li>
              {{ end }}
            </ul>
          {{ end }}
        </li>
      {{ end }}
    {{ end }}
  </ul>
</aside>

This renders like this:

  • Introduction
    • S1 Index
    • S2 Index
    • S3 Index
    • Glossary
  • S1 Index
    • S1 Page 1
    • S1 Page 2
  • SS1 Index
    • SS1 Page 1
    • SS1 Page 2
  • S2 Index
    • S2 Page 1
    • S2 Page 2
  • S3 Index
    • S3 Page 1
    • S3 Page 2

There are a few problems I just can’t fix:

  • The subdirectories shouldn’t be listed as sub-items of Introduction.
  • There shouldn’t be a blank sub-item of Introduction.
  • The Glossary page should be listed at the bottom of the tree, and is weighted accordingly.
  • S11 should be a sub-item of S1, not on the same level as it.

Any ideas how to fix this?

Looks like you are searching for that one:

Dunno if this is handled. But guess so according to your first printed ul.

1 Like

Thank you @irkode, this was exactly what I needed; I just couldn’t find it for the life of me. For anyone who may find this thread in the future:

  • This solution is indeed listed in order of weight by default.
  • To make the file tree step through only a specific content type (in my case, only docs articles and not blog posts), try changing {{- range .pages }} to something like {{- range where .pages "Type" "docs"}}
  • The blank entry at the bottom of the list was caused by content/docs/README.md, because my content/docs directory is actually a git submodule. Adding ignoreFiles = "README.md" to hugo.toml fixed this.
1 Like

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