Dynamic filename in exists function

Hi Guys.

I am trying to find out if a file exists but the name of the file is dynamic dependant on a param set in the front matter of the article.

At the top of the content .md file I have set this variable

filehash : "87Hr5342dd42D5We6dq7w11d"

Now, in the single.html file I am using the file exists function like so:

{{ if (fileExists "/specs/project-" +  .Page.Param.filehash + ".md") -}}
    file exists
{{- end }}

However I am getting this error:

illegal number syntax: “+”

Any suggestions?

You’ll need to use printf to format the .md reference.

I.e. something like
{{ $hash := .Params.filehash }}
{{ $md := printf “%s” (print “/specs/project-” $hash “.md”) -}}

{{ if (fileExists $md) -}}
file exists
{{- end }}

Please note that this is untested (I’m still learning), but I believe something along these lines might work. Hopefully, I have got you a little closer to solving this.

Thanks for your reply. With your sultion I get this:

<Param.filehash>: wrong number of args for Param: want 1 got 0

any ideas? I’m also very new :confused:

I updated param to params. Made a typo when i first posted. Can you check again please.

1 Like

That worked. Thank you.

{{ $md := printf “/specs/project-%s.md” $hash -}}

1 Like

Probably wrap it in a with because, it will fail when there are pages without the hash.

{{ with .Page.Params.filehash }}
      {{ $hash := . }}
      {{ $path := print "/specs/project-" $hash ".md" }}
      {{ if (fileExists $path) }}
         File Exists
      {{ end }}
{{ end }}

The + concatenation does not work.

1 Like