Here’s a quick HTML template snippet to do something I find is quite a common
task in a Hugo site: show a list of other pages that share a taxonomy term with
the current page.
It’s probably a good idea to refresh your memory of how taxonomies work in
Hugo if you’re feeling rusty.
The snippet is just:
{{ if isset .Params "tags" }}
{{ $tagTitle := index .Params.tags 0 }}
{{ $currentLink := .Permalink }}
<h2><small>Tag:</small> {{ $tagTitle | title }}</h2>
<ol>
{{ range (index .Site.Taxonomies.tags ($tagTitle | urlize)).Pages.ByTitle }}
<li>
{{ if eq $currentLink .Permalink }}
{{ .Title }} <small>(this page)</small>
{{ else }}
<a href="{{ .Permalink }}">
{{ .Title }}
</a>
{{ end }}
</li>
{{ end }}
</ol>
{{ end }}
The example taxonomy here is “tags”, but it could be any taxonomy. We check if
tags are set on this page, and then go ahead with showing other pages that share
a tag term with the current one if so.
The $currentLink := .Permalink part is to allow determining which page in the
list is the current page with if eq $currentLink .Permalink in the range loop,
so that we can render it as plain text and not a link, and add the “(this page)”
hint after it.
Note that this example only takes the first tag term and shows the list of pages
for that. If we want to show a list of pages for each tag on the post, we could
wrap this in one outer loop along the lines of this:
{{ $currentLink := .Permalink }}
{{ range .Params.tags }}
{{ $tagTitle := . }}
<h2><small>Tag:</small> {{ $tagTitle | title }}</h2>
<ol>
{{ range (index .Site.Taxonomies.tags ($tagTitle | urlize)).Pages.ByWeight.Reverse }}
<li>
{{ if eq $currentLink .Permalink }}
{{ .Title }} <small>(this page)</small>
{{ else }}
<a href="{{ .Permalink }}">
{{ .Title }}
</a>
{{ end }}
</li>
{{ end }}
</ol>
{{ end }}
That would duplicate pages that share more than one tag term with the current
page, though, so you might want to do something smarter with getting a unique
set of shared tasks if that would be more effective for your use case.
Hugo has a handy taxonomy
weight
feature that lets you apply an ordering to pages within a taxonomy term like
this. You just add a key like {plural taxonomy name}_weight in the page’s
front-matter:
The pages in that taxonomy term will then be naturally ordered in ascending
weight.
This approach can be used to build a Series taxonomy in a Hugo site.
I use this approach on a few static sites, including Chinese Boost
Grammar, East Asia
Student, Moment Wall
Art and this site.
View post:
Showing other pages with the same taxonomy term in Hugo
|