I have a slight problem with fileExists in an if condition.
I’m running the code listed below from _default/single.html template and the image file, for which existence I check against, does exist. In the second line I’m printing out content of $header_img variable, which holds file’s absolute path, and it is seems to be correct, because by using this URL I can open the image in my browser. However, for some reason this condition never evaluates as true.
I checked this code many times for possible typos or other mistakes, but I didn’t catch anything suspicious. Could you please take a look at it and see what’s wrong with it?
{{- $header_img := (path.Join .Permalink "header-image.jpg") -}}
{{ $header_img }} <!-- This returns a valid absolute URL of the image file. -->
{{ if (fileExists $header_img) -}}
<p>true</p>
<img src="header-image.jpg" class="post-header-image" width="1280" height="400">
{{- end }}
I see. So, from what I understand, if my image file resides in https://hugosite.com/blog/postn/header-image.jpg (/content/blog/postn/header-image.jpg before I build the site), and this is the contents of $header_img variable from my first post, then the following code:
{{- $header_img := (path.Join .Permalink "header-image.jpg") -}}
{{ $header_img }} <!-- This returns a valid absolute URL of the image file. -->
{{ if (fileExists $header_img) -}}
<!-- ... -->
{{ end }}
will never be evaluated as true because it tests against the existence of https://hugosite.com/https://hugosite.com/blog/postn/header-image.jpg file?
In your example, $header_img evaluates to https://hugosite.com/blog/postn/header-image.jpg which is not a valid file system path. The fileExists function tests where a file resides on the file system, not the URL from which it is served.