Check if file exists in a template?

I’m trying to check if a file exists, and if it does, display it in the template.

In my /layout/books/single.html I have:

{{ if (fileExists "cover.jpg") -}}
   <img src="cover.jpg" />
{{- end }}

My content directory has:

/content/books/book-one/index.md
/content/books/book-one/cover.jpg

However the image isn’t displayed nor is the img tag present in view source. I’m not sure where the fileExists check will be relative to. The image file file does exist in the public directory

/public/books/book-one/cover.jpg

How can I conditionally display an image based on whether the file is there or not?

Since your image is inside the page bundle, you can use .GetMatch: https://gohugo.io/content-management/page-resources/#methods

So, something like

{{ with .Resources.GetMatch "cover.jpg" }}
<img src="{{ .Permalink }}" >
{{ end }}

Out of curiosity is there a reason my fileExists check failed?

You probably want to test on this path:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.