How to check whether a file exists in the folder?

I have tried this option:

{{ $files := readDir "static/images/" }}
{{ if in $files "avatar.png" }}
{{ printf "%v" $files  }}
{{ end }}

readDir generate the list of files from the folder that i want, but I do not know how to compare it with a string.

The best solution I’ve found is this:

{{ if (where (readDir $directory) "Name" $filename) }}
{{ $filename }} was found in {{ $directory }}
{{ end }}

The problem that this solves is one of matching a particular field (the filename) from a struct (os.fileStat) for every instance of the struct in an array (result of readDir). I could find no other way to do this in the template system. What I wanted to do was:

{{ if in {{ apply (readDir $directory) "index" "." "Name" }} $filename }}
{{ $filename }} was found in {{ $directory }}
{{ end }}

But the index function does not work on structs.

2 Likes

Thank you, this example actually works.

{{ $directory := "static/images/" }}
{{ $filename := "avatar.png" }}
{{ if (where (readDir $directory) "Name" $filename) }}
{{ $filename }} was found in {{ $directory }}
{{ end }}
3 Likes

Just to clear up potential confusing, the above solution won’t check if a file exists or not, without error (in other words, if file doesn’t exist, readDir will return an error).

This looks like new way to go - https://gohugo.io/functions/fileexists/

2 Likes