How to Recursively List all Files in a Directory

I thought this snippet might be worth sharing.

If you are writing a Hugo tutorial it’s important to show the file structure, and one of the ways to do that is to make a nested list with <ul> and <il>, like the following:

  • _index.md
  • homepage
    • about.md
    • index.md
    • work.md
  • post
    • _index.md
    • emoji-support.md
    • markdown-syntax.md
    • rich-content.md

To generate the lists programmatically, here’s a helpful partial called partials/walk.html that recursively visits each directory:

{{$path := .}}
<ul>
    {{range (readDir $path) }}
        <li> {{.Name}}
        {{if .IsDir}}
            {{ partial "walk.html" (path.Join $path .Name) }}
        {{end}}
        </li>
{{end}}    
</ul>

To use it, just pass a string to the partial, like this:

{{ partial "walk.html" "content"}}

"content" can be any directory from your project, including ".". The list can be styled using CSS.

Hopefully this is of use to someone!

5 Likes