.If FileExists Directive

In my directory template I would like to check if there is a README.md within the folder and include and render it if so. I’ve tried {{.If (.Include 'README.md')}} and just including it but both throw errors.

Is there a way to do something like {{.If (.FileExists 'README.md')}}? I’m not familiar with Go but I can pick up what I need to.

After doing a bit of research into this, I think it’s possible.

Since you get a slice out of the .Files function, you should be able to range it and then check if the file is README.md.

The only problem I can’t get around is that I think it requires foreknowledge of the directory you need to search, because .Files takes an argument (the directory in question). I can’t see any easy way to get this from other functions in a format that is easily fed to .Files.

The following untested example is about as far as I’ve thought through this concept:

{{range .Files "/some/directory"}}
	{{if eq . "README.md"}}{{.Include "README.md"}}{{end}}
{{end}}

Some testing would need to be done to make sure the output of .Files matches what you’re testing for, I expect.

https://caddyserver.com/docs/template-actions

This would probably be much easier to achieve in actual Go code than in a template, unfortunately.

1 Like

This was exactly the clue I needed. Thanks so much. I had to modify it a little bit. I would appreciate you letting me know if I’m committing a faux pas here. I’m kind of stabbing in the dark.

{{range .Files .URI}}
  {{if eq . "README.md"}}
    {{$.Markdown (print $.URI "README.md")}}
  {{end}}
{{end}}

Give it a shot, but I don’t know if the output from .URI is going to suit the required input for .Files, especially if there are fragments or queries involved. It’ll definitely wig out if you feed it a file request. If you can guarantee its only for directory requests, it might work sometimes and fail other times. But that’s what I had in mind, yeah.

You could look into rewriting directory requests to make sure the URI doesn’t contain fragments/queries, but I don’t know if .URI checks the rewritten or the pre-rewritten URI (you need, for example, a specific Placeholder to access the rewritten version in the Caddyfile).

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