Hello!
I need to pass a list of files in a directory and its subdirectories to a script. For example, if the directory is set to “dir1” and looks like this:
dir1/
dir2/
file1
file2
file3
I want the list to look like:
dir2/file1
dir2/file2
file3
Right now I can’t figure out a simple way to do this; admittedly I don’t understand Hugo’s file functions very well. Would someone point me in the right direction?
Thanks!
Do you want a recursive list of directories and files (i.e., the file system), or a recursive list of sections and pages (i.e., the content structure)?
Directories and files; I’m working with non-content files.
From any template
{{ partial "display-file-structure.html" "content" }}
layouts/partials/display-file-structure.html
{{ range readDir . }}
{{ $path := path.Join $ .Name }}
{{ $path }}
{{ if .IsDir }}
{{ partial "display-file-structure.html" $path }}
{{ end }}
{{ end }}
If you want to create a slice of entries, where each entry excludes the entry point…
{{- range readDir . }}
{{- $path := path.Join $ .Name }}
{{- printf "%s\n" $path }} <----- notice the newline
{{- if .IsDir }}
{{- partial "display-file-structure.html" $path }}
{{- end }}
{{- end -}}
Then do:
{{ $dir := "content" }}
{{ $list := partial "display-file-structure.html" $dir }}
{{ $list = split (trim $list "\n") "\n" }}
{{ $list = apply $list "strings.TrimPrefix" (printf "%s/" $dir) "." }}
That gives you a data structure like this:
[
"books",
"books/book-1.md",
"books/book-2.md",
"books/fiction",
"books/fiction/book-3.md",
"films",
"films/film-1.md",
"films/film-2.md"
]
1 Like
Thanks! This works very well.
One more thing: how can I exclude directories from the slice of entries? I only want files.
Basically, for your second example, I want it to look like this:
[
"books/book-1.md",
"books/book-2.md",
"books/fiction/book-3.md",
"films/film-1.md",
"films/film-2.md"
]
Thanks!
In the partial, print the path only when .IsDir is false:
{{- range readDir . }}
{{- $path := path.Join $ .Name }}
{{- if .IsDir }}
{{- partial "display-file-structure.html" $path }}
{{- else }}
{{- printf "%s\n" $path }}
{{- end }}
{{- end -}}
system
Closed
June 30, 2023, 3:18am
7
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.