Study Guide: Directory Listings in Hugo
How to create a list of files from a directory in Hugo.
Example Shortcode /layouts/shortcodes/dir_list.html
{{/* The value of $path is passed when the shortcode is called. See below. /*}}
{{ $path := .Get "path" }}
{{/* Example for accessing assets directory. /*}}
{{ $filepath := printf "assets/etc/%s" $path }}
{{/* Example for accessing static directory. /*}}
{{ $filepath := printf "static/%s" $path }}
{{ $files := readDir $filepath }}
{{ $ext := default "-" (.Get "type" )}}
{{- if (fileExists $filepath) }}
<div>
{{- range $files }}
{{- if (and (ne (substr .Name 0 1) "_") (not .IsDir)) -}}
{{- $f := resources.Get (printf "%s/%s" $filepath .Name) -}}
{{- $e := findRE "\\w+$" .Name -}}
{{- if (or ( eq $ext "-") (in $e $ext) -)}}
<a href={{$f.Permalink }} type=text/plain download>{{ .Name }}</a>
{{- end -}}
{{- end -}}
{{- end }}
</div>
{{- end }}Call the shortcode from within a content item
{{ < dir_list path="mydirectory" type="jpg" >}}Related Hugo functions
Related Go functions
More information
- https://discourse.gohugo.io/t/list-files-in-a-directory/21258
- Go Template functions
- Go Template OS functions
Related Content
Source: //study/hugo/hugo-directory-listing/
