fileExists function not working as expected

I am trying to debug a code snippet which goes as follows:

{{- if and (fileExists "/css/highlight.css") .IsPage -}}
	<link rel="stylesheet" type="text/css" href="/css/highlight.css">
{{- end -}}

The weird thing which is happening here is that the conditional expression fileExists "/css/highlight.css" results to false even though I am able to load that file in my browser in that path. Am I missing something here?
Also, don’t know if it’s worth mentioning or not, I have set themesDir to ../../.

Live website undergoing issue:
Concerned code:

(fileExists "static/css/highlight.css")

That too, didn’t make a difference. Also, I am wondering why need to add static to the path considering Hugo can access the file even without adding the static.

I use this function in a variety of templates and it works great. You have an error somewhere in the syntax. Create a simple code for debugging and find the error.

{{- if (fileExists "static/css/highlight.css") -}}
{{- end -}}

I use Hugo 0.42.2

I updated my Hugo version and still no change. :slightly_frowning_face:

I think it has something to do with the change in root directory. Because I changed the themesDir variable. Any way to refer to the root directory of Hugo?

The fileExists function looks for a file on your computer, in the Hugo project. But loading the same file in the browser is different and based on how Hugo rendered it. So do don’t pass fileExists the path to the file as it appears with hugo server but use the path on the disk.

For instance:

  • A file in /static/css/my-style.css is served as /css/my-style.css by Hugo server. But for fileExists to find the actual file, you’ll need to include the /static/ folder in the path.

That code checks for fileExists "static/css/highlight.css", but if I look in the /static/css/ folder of the theme there is no highlight.css file, only a site.css file.

I tried moving highlight.css to that folder and it failed as well. What’s confusing for me is that when I place it in exampleSite/static/ it works. But why does Hugo treat the parent static folder as static folder too, isn’t it outside the project folder, i.e. example site?
In that case shouldn’t I be required to place my site.css file in the project static folder as well?

This also confuses me. Can it be caused by settings in your configuration file? That is, if you set exampleSite as the website source in the configuration file, then it might explain why fileExists only looks there. (Even though that still would be odd, I agree.)

1 Like

I haven’t set anything unusual in my configuration file other that changing the themesDir value to ../../ which I think shouldn’t affect my project root.

I see that you have been using an absolute path (beginning with /) while others have been using a relative path. Could that be making a difference?

No, it isn’t due to relative path.