Hugo taxonomy crosswalk

Fri, Dec 30, 2016

My Hugo theme has two taxonomies - topics and tags. For a given topic I wanted to be able to render a list of tags relevant to that topic. It took me a little while, but here’s the template code I came up with to accomplish this.

Note: this code lives within my “topic” index template: layouts/taxonomy/topic.html which provides critical context.

 {{- $baseURL := .Site.BaseURL }}
 <nav>
 {{- $.Scratch.Set "tags" (slice) }}
 {{- range .Data.Pages }}
   {{- range $term := .Param "tags"  }}
     {{- if not (in ($.Scratch.Get "tags") $term)   }}
       {{- $.Scratch.Add "tags" (slice $term) }}
     {{- end}}
   {{- end  }}
 {{- end }}
 {{- range sort ($.Scratch.Get "tags") }}
   <a href="{{ $baseURL }}/tags/{{ . | urlize }}">{{ . }}</a>
 {{- end }}
 </nav>

As you can see the purpose here was to render the list of relevant tags inside of a <nav> block as a set of links to each tag’s list node. The thing that made this trickier than I’d anticipated was the need for some more-or-less ephemeral variable/data structure in which to store the relevant tags as it walks through the topic’s pages. This is where the $.Scratch variable comes in. Check out the Hugo doc on Scratch.

I hope this little snippet is helpful.

Cheers!