How to Get All Pages with the Same Tag in Hugo
In my Hugo site, I wanted a Related Content
section that lists all other posts with the same tag as the current page being viewed.
For instance, if the post that’s currently being viewed contains the tag featured
, then I want to list all other pages on my site that also contain the featured
tag.
While Hugo provides an efficient way to access a page’s related content, I wanted a method that was more configurable for the future.
Naturally, I looked to single.html
, since that’s where my individual post content is rendered (this may differ for another Hugo site).
1. Get Tags of the Current Page
The first step is to get all the relevant tags for the current page.
For this, we can use .GetTerms "tags"
, which will return a list of strings. We can access .LinkTitle
to get the tag in each iteration.
{{ range (.GetTerms "tags") }}
{{ $currTag := .LinkTitle }}
{{ end }}
2. Filter Pages by Tag
The next step is to get only the pages that contain that tag.
Suppose we knew exactly which tag to filter by, and suppose it’s featured
. In that case, we can simply access .Site.Taxonomies.tags.featured.Pages
to access those pages.
{{ $taggedPages := index .Site.Taxonomies.tags.featured.Pages }}
However, we’d like to make this dynamic. Let’s use the $currTag
variable from above.
{{ $taggedPages := (index .Site.Taxonomies.tags (lower $currTag)).Pages }}
3. Iterate Through Tagged Content
Now, we can simply iterate through $taggedPages
, and render out the correct links in an unordered list <ul>
.
<ul>
{{ range $taggedPages }}
<li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
4. Final Solution
Now, let’s put everything together.
The only issue is that $taggedPages
will return the current page as well. We don’t want to add a list item <li>
if the page in the current iteration of $taggedPages
is the same as the current page. I’ve added that check in the following code.
{{ $currPermalink := .Page.RelPermalink }}
{{ range (.GetTerms "tags") }}
{{ $currTag := .LinkTitle }}
{{ $taggedPages := (index .Site.Taxonomies.tags (lower $currTag)).Pages }}
<ul>
{{ range $taggedPages }}
{{ if not (eq .RelPermalink $currPermalink) }}
<li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
{{ end }}
</ul>
{{ end }}