How to check if file exists using {{ .Page.Title }} in fileExists?

I need to check if pdf file exists in my folder. This code works if i write is using filename:

{{ if (fileExists "static/MyFile - Schematic.pdf") -}}
    <li>{{ .Page.Title }} - Schematic (PDF)</li>
  {{- end }}

And it does not work if i write:

{{ if (fileExists "static/attachments/{{ .Page.Title }} - Schematic.pdf") -}}
    <li>{{ .Page.Title }} - Schematic (PDF)</li>
  {{- end }}

So my question is how can i use {{ .Page.Title }} in fileExists function?

My .Page.Title have value of MyFile.

With the setup you described above you cannot use .Page.Title because with the fileExists function you are looking for a PDF located under the staticDir and therefore Hugo cannot know under which Page is this file referenced.

You need to rethink your project’s structure.

Have a. look at Page Bundles and Page Resources.

You need to “print” out the filename. If .Page.Title exists and has MyFile as value then the following should work:

{{ if (fileExists (printf "static/attachments/%s - Schematic.pdf" .Page.Title) -}}

A possible issue I would expect might be the spaces in the file name. Maybe try to work without them so you don’t need to find out how to encode the search.

2 Likes

Thanks.

I im new to Hugo (discovered last week)…and have done 50% of page for my electronics blog…i customize template Dimension and your code works excellent, works with space between and - in filename so this solution works wonderfull.

Thanks.

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