Hugo: Get all posts with a target tag set

2020.01.27 | 208 words |

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

 

About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus