Pass directory-contents to javascript

I want to read a directory (an image directory) and pass the filenames on to a javascript array, so I can let a script choose a random image from the list to display each time the page is loaded. Is that possible?

Thanks. Yes, I knew about readDir, but I didn’t see how to use it exactly. I’ve figured it out, this works:

<script>
    let imgArr = [{{ range(readDir "static/img") }}{{ .Name }}, {{ end }}];
</script>

But an auto-formatting editor like VSC will put unwanted white-space between (some) ‘{{’ or ‘}}’, so it’s possible that you need another editor.

What you wnt to do is something ala this:

{{ $names := slice }}
{{  range readDir "foo" }}
{{ $names = $names | append .Name }}
{{ end }}
{{ $json := $names | jsonify }}

1 Like