List files in a directory

Hi,

I’m trying to create a template or shortcode that lists the files in a directory.

My particular use-case is that I’d like to have a page that lists the contents of a directory full of .wav and .mp3 files. Each file does not require its own page, so having the list template/shortcode display a direct link to the file is what I’m trying to do.

I’m having a bit of difficulty finding the right starting point to accomplish this. I’ve found documentation relating to .ResourceType / .MediaType (https://regisphilibert.com/blog/2018/01/hugo-page-resources-and-how-to-use-them/). However I’m having a hard time figuring it out and implementing it on my site.

Ideally, I’d like to figure this out on my own, as I’m mainly using Hugo as a hobby. If .ResourceType / .MediaType is indeed the correct direction to go in, please let me know. If not, all I ask is a point in the right direction, and I can eventually figure it out from there. Thank you!

I would go one of these routes:

(1) for a given page, walk its .Resources, then grab each .Permalink; or

(2) construct the URL yourself using local file templates https://gohugo.io/templates/files/#readout

1 Like

a littel sample :wink:
I use this to make a linux doc (with sym link /etc to assets/etc)

shortlist.html shortcode

{{ $path     := .Get "path" }}
{{ $filepath := printf "assets/etc/%s" $path }}
{{ $files    := readDir $filepath }}
{{ $ext := default "-" (.Get "type" )}}
{{ if (fileExists $filepath)}}
<div class="pa2 mh4 ba">
{{- range $files }}
	{{ if (and (ne (substr .Name 0 1) "_") (not .IsDir)) }}{{ $f := resources.Get (printf "/etc/%s/%s" $path .Name)}}
		{{ $e := findRE "\\w+$" .Name }}
		{{ if (or ( eq $ext "-") (in $e $ext) )}}
			<a class="w-auto pr2" href={{$f.Permalink }} type=text/plain download>{{ .Name }}</a>
		{{end}}
	{{end}}
{{- end }}
</div>
{{end}}

how I call it

{{< lshortlist path="apache2/sites-enabled" type="conf">}}

1 Like

Thank you so much! I’ll be testing this out shortly. I truly appreciate the time you took to help me, both ju52 and zwbetz. You guys are awesome!

So I tried your shortcode and couldn’t get it to function properly. After replacing your target directory with mine (static/audio), the page properly renders but does not list the files. Ju52, if you would be so kind, can you explain the string “/etc/%s/%s” found on line 10? I’m having a hard time understanding how to parse in my directory at that point. Would it be “/static/%s/%s” as to reflect my target directory?

My apologies for the lack of understanding, I’m in no way a programmer, ha.

$path ist the parameter from the shortcode
.Name comes from the RANGE operation, range goes over files, .Name ist simply the filename
Print puts all together

The call should be
{{< shortlist path=“apache2/sites-enabled” type=“conf”>}}

Forget to delete the first “l”

to go to static

{{ $filepath := printf “static/%s” $path }}