Essay record

Hugo: Get all posts with a target tag set

Record
Essay / / 1 min read / 212 words
Tags
hugo
On this page2 sections / +

DISCLOSURE: Some links may be affiliate links. Details

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

Built with CloudSeed Rust