I’m writing a template for Taxonomy list (one that is used for rendering /PLURAL/TERM). In that template, I’d like to get previous and next term within single Taxonomy. Is there a sane way to do this?
I’ve ended up with this code:
{{ $taxonomy_name := "hg" }}
{{ $term_pages := index .Data $taxonomy_name }}
{{ $firstpage := index $term_pages 0 }}
{{ $term_name := index (index $firstpage.Page.Params $taxonomy_name) 0 }}
{{ $all_terms := index .Site.Data $taxonomy_name }}
{{ $.Scratch.Set "previously_seen" "" }}
{{ range $key, $value := $all_terms }}
{{ $prev := $.Scratch.Get "previously_seen" }}
{{ if eq $key $current_term_name}}Previous term: {{ $prev }}<br>{{ end }}
{{ if eq $prev $current_term_name }}Next term: {{ $key }}<br>{{ end }}
{{ $.Scratch.Set "previously_seen" $key }}
{{ end }}
This works, but is ugly. I’ve tried using a normal variable instead of Scratch, but it looks like the scope of variable set inside a range loop is limited to single iteration.
I know this post is old, but I kept coming across it when searching for examples while rebuilding my portfolio in Hugo. Here’s a solution I came up with that’s worked for me in case it helps someone else.
In my site config I use this to define taxonomies and set their path beneath a /portfolio area on my site:
Then for pages such as /portfolio/clients/acme or /portfolio/markets/b2b, the template at layouts/term/list.html is used and I include this as a partial:
{{ $taxonomy := .Section }}
{{ $terms := (where .Site.Pages "Type" "in" $taxonomy).ByTitle }}
{{ $firstTerm := index $terms 0 }}
{{ $lastTerm := index $terms (sub (len $terms) 1) }}
<!-- initialize prev/next vars with a default value in page scope -->
{{ $prevTerm := . }}
{{ $nextTerm := . }}
<!-- test if a prev/next term currently exists and set, -->
<!-- else loop through list by setting to show last/first term -->
{{ with $terms.Prev . }}
{{ $nextTerm = . }}
{{ else }}
{{ $nextTerm = $firstTerm }}
{{ end }}
{{ with $terms.Next . }}
{{ $prevTerm = . }}
{{ else }}
{{ $prevTerm = $lastTerm }}
{{ end }}
<section role="navigation" aria-label="Previous/Next {{ title (singularize $taxonomy) }}" class='container prev-next'>
<a href="{{- $prevTerm.RelPermalink -}}" class="previous-term" rel="prev">
<span class="section-label"><span class="order-label">Prev </span>{{- title (singularize $taxonomy) -}}</span>
<span class="truncate">{{- $prevTerm.Title -}}</span>
</a>
<a href="{{- $nextTerm.RelPermalink -}}" class="next-term" rel="next">
<span class="section-label"><span class="order-label">Next </span>{{- title (singularize $taxonomy) -}}</span>
<span class="truncate">{{- $nextTerm.Title -}}</span>
</a>
</section>