Hugo: Get all posts with a target tag set

Published: 2020-01-27 19:15:16 -0500 -0500

Reading time: 2 mins (208 words)

Tags: hugo


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?


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"))

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus