Hugo readDir and generating dynamic JSON

September 11, 2017

Context
I’m using Hugo to generate a JSON feed for images + meta data. Part of the JSON is showing all the images in a directory. So:

static
  |__color
        |__blue
            |__blue_close_1.jpg
            |__blue_far_1.jpg
        |__green
            |__green_close_1.jpg
            |__green_far_2.jpg

To build a JSON template that lists the .jpg files in each directory, I need to write a generic readDir statement, which wasn’t possible by usual means. E.G these DO NOT work:

{{ $colorDir := "/static/color/"{{ .Title }} }}
{{ $colorDir := "/static/color/{{ .Title }}" }}
{{ $colorDir := "/static/color/.Title" }}
{{ $colorDir := "/static/color/" .Title }}

{{ range := (readDir $colorDir ) }} {{ .Name }} {{ end }}

How to do this was buried in the support forums. Any of these work:

{{ $colorDir := (printf "/static/color/%s" .Title) }}
{{ $colorDir := .Title | printf "/static/color/%s" }}

{{ range := (readDir $colorDir) }} {{ .Name }} {{ end }}

printf is able to generate the correct url, and then that variable is usable in readDir.