Check if a file exists?

I’m building a template that displays images of guests on our show based on frontmatter; that is, there is an array in the frontmatter that lists the guest names. The name is used to populate some content, and then it also uses that to find the image file to display.

As we go through migration, some guests will not have images. I’d like to be able to check to see of “static/guests/myname.png” exists, and if not, have it instead render “static/guests/default.png”. How can I do a file check in a template, if at all possible?

1 Like

In 0.15-DEV a hacky way would maybe be to use the readDir func.

I think that it’ll actually take me less time/effort/troubleshooting to migrate the images/make new ones.


Okay, how about checking if a directory exists? I’m not being snarky - I want to do this.

readDir gives an error in this case. I suppose I can ignore the error?


I also would like to be able to check if a directory exists.

Actually, what I’m trying to do is have my template include any partials that exist in /layouts/partials/head/ (to allow users to insert some custom content in the <head> of every page without having to modify the template files).

{{ range readDir "/layouts/partials/head/" }}{{ partial .Name }}{{ end }}

works great if the directory /layouts/partials/head/ exists, but throws an error if this directory doesn’t exist.

Any ideas? (apart from using a param to enable/disable this code)

Another method