Hugo: Get all posts with a target tag set

Date: 2020-01-27 | hugo |

problem

I'm using the static generator Hugo to build my sites. For one of my templates, I want to get all pages with "TARGETTAG" set. How can I get all the pages in my site that has the given tag?

solution

I recently figured this out as part of building a simple related content partial for my blog. Essentially we can accomplish this by searching through all pages (really RegularPages is what you want) on the site and just checking if any of their tags are equal to your TARGETTAG.

Here's a code example:

{{ $scratch := newScratch }}
<!-- to check against multiple target tags, add more tags next to "TARGETTAG" -->
{{ range (where .Site.RegularPages "Params.tags" "intersect" (slice "TARGETTAG")) }}
    {{ if not ($scratch.Get "test") }}
        {{ $scratch.Set "test" (slice .) }}
    {{ else }}
        {{ $scratch.Add "test" . }}
    {{ end }}
{{ end }}

<!-- this "test" scratch variable will have all pages with `TARGETTAG` set -->
{{ $scratch.Get "test" }}

If you wanted to get posts with tags in an array of target tags vs checking only against one, then you could just add the other target tags next to "TARGETTAG" in line 2 (e.g. (slice "TARGETTAG") would become (slice "TARGETTAG" "TARGETTAG1" "TARGETTAG2"))

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.