Wrap-around with .PrevInSection / .NextInSection?

My site uses .PrevInSection and .NextInSection to create links from one page to the next. What I’d like to do is go ‘next’ from the last page and wrap-around to the first, and vice-versa.

If I could find a way to access the first page (in the current sort order), which I’ll call .FirstInSection, I could do something like:

{{ with .NextInSection }}
    <a href="{{ .Permalink }}">{{ .Title }} &#10094;</a>
{{ else }}
    {{/* This doesn't work, because there's no such thing as '.FirstInSection' (yet) */}}
    <a href="{{ .FirstInSection }}">{{ .FirstInSection.Title }} &#10094;</a>
{{ end }}

Alternatively, I could add a wrap parameter to .PrevInSection and .NextInSection.

Is there already a way to do this, or shall I invent one?

Partially answered:

Thanks for your reply, but it doesn’t really help.

The code already knows if it’s on the last page because .NextInSection returns nil.

I think this should be correct:

{{ $next := .NextInSection }}
{{ if not $next }}
{{ $next = index .CurrentSection.RegularPages 0 }}
{{ end }}

Or, thinking about it, I think NextInSection is working on the root section, so this then:

{{ $next := .NextInSection }}
{{ if not $next }}
{{ $next = index .FirstSection.RegularPagesRecursive 0 }}
{{ end }}
2 Likes

Thanks, Bjørn, that’s excellent. Both of those seem to give the same result for me.

I can get the last page too with a bit of arithmetic. Now the whole thing looks like this:

<div class="row">
  <div class="col align-self-baseline text-left py-2">
    {{ $prev := .PrevInSection }}
    {{ if not $prev }}
      {{ $prev = index .CurrentSection.RegularPages 0 }}
    {{ end }}
    {{ with $prev }}
      <a href="{{ .RelPermalink }}">{{ .Title }} &#10094;</a>
    {{ end }}
  </div>
  <div class="col align-self-baseline text-center bg-primary py-2">
    <a href="/">Gallery</a>
  </div>
  <div class="col align-self-baseline text-right bg-primary py-2">
    {{ $next := .NextInSection }}
    {{ if not $next }} 
      {{ $next = index .CurrentSection.RegularPages (sub (len .CurrentSection.RegularPages) 1) }}
    {{ end }}
    {{ with $next }}
      <a href="{{ .RelPermalink }}">&#10095 {{ .Title }}</a>
    {{ end }}
  </div>
</div>
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.