Give a dynamically generated path to readDir

I have a path to a gallery defined in my content file’s frontmatter. This is not the path to the directory itself- that would be static/images/gallery/w480

+++
gallery_path = "/images/gallery"
+++

I want to use a Hugo template to add to the beginning and end of gallery_path and then use that path to get the list of files.

{{ $full_path := printf "%s%s%s" "static" .Params.gallery_path "/w1440" }}
{{ $.Scratch.Set "scratched_path" $full_path }}
{{ $url := $.Scratch.Get "scratched_path"}}
{{ $url }}
{{ $files := readDir $url }}

The fourth line above {{ url }} prints the path correctly as static/images/gallery/w480. However, when the readDir line is included, I get the following error:

execute of template failed: template: accommodation/single.html:16:21: executing "main" at <readDir $url>: error calling readDir: Failed to read Directory static%!s(<nil>)/w1440 with error message...

How can I resolve this and read the directory based on the constructed path?

Your problem is that some pages does not have the gallery_path defined. What you can do is something ala:

{{ if  .Params.gallery_path }}
{{ $full_path := printf "%s%s%s" "static" .Params.gallery_path "/w1440" }}
{{ $.Scratch.Set "scratched_path" $full_path }}
{{ $url := $.Scratch.Get "scratched_path"}}
{{ $url }}
{{ $files := readDir $url }}
{{ end }}

That solved it- thank you!