Using fileExists for to configure custom headers for tags and categories

I wanted to have custom headers for categories and tags, with as little configuration as possible.

The solution I found was this, check if there is a file that matches the taxonomy name and term, and if so, use it.

Files are placed in /content/static/tags/xmas.jpg for example.

{{ $taxonomyImage := printf  "static/%s/%s.jpg" .Data.Plural .Data.Term  }}
<div class="page-header-image" style="background-image: url('{{ if (fileExists $taxonomyImage) }}{{ $taxonomyImage | absURL }}{{ else }}{{ partial "header-image.html" . }}{{ end }}');">

On my site it looks like this:

1 Like

Nice! I’ve thought of this one, but never build anything. I like this use case, because certain collections of content are built this way, and having Hugo not trip up on missing assets and instead doing the right thing is great! :slight_smile:

There is however another solution for this, that includes more files. An _index.md file placed in content/tags/christmas/_index.md will allow you to set the proper resources to build a header.

If you are running a bilingual site, like me, this means you will need to add an _index.pt.md. As an alternative, I have used symlinks for this use case.