How to link the next page with the same tag?

I would like to create a Next link on all pages that point to the next page having the same tag. The default Next points to the next entry chronologically. I would like to filter out entries that are not related tag-wise. The code .Site.RegularPages.Related . | first 3 gives me the previous related 3 entries. How do I get the next ones instead?

How can I do this?

Best regards,
Joannes Vermorel

By default, .Site.RegularPages.Related includes pages where .Date is older than the current page’s .Date . To include both older and newer pages:

[related]
  includeNewer = true

See https://gohugo.io/content-management/related/#default-configuration.

Thanks a lot for your follow-up. It’s very appreciated. However, if includeNewer = true is used then .Site.RegularPages.Related . | first 3 will give me top 3 most recent (absolute), not the next 1 more recent. In a way, I am looking for an alternate of .Site.RegularPages.Related where the inequality comparison with .Date is inverted. Is there any way to implement this using the Hugo syntax?

I want to make sure I understand what you need.

Let’s say I’m on the page “Post 3”, with the tag “foo”, dated 2021-04-10, and the related pages are:

Post 5 (2012-04-12)
Post 4 (2012-04-11)
Post 2 (2012-04-09)
Post 1 (2012-04-08)

You want a reference to Post 4. Correct?

1 Like
{{ $r := .Site.RegularPages.Related . }}
{{ $pRelatedPrev := index (first 1 (where $r "Date.Unix" "lt" .Date.Unix)) 0 }}
{{ $pRelatedNext := index (first 1 (where $r "Date.Unix" "gt" .Date.Unix).Reverse) 0 }}

{{ with $pRelatedPrev }}
  <a href="{{ .RelPermalink }}">Previous Related Page</a>
{{ end }}

{{ with $pRelatedNext }}
  <a href="{{ .RelPermalink }}">Next Related Page</a>
{{ end }}
2 Likes

I suspect a better way would be to:

  • Sort .Site.RegularPages.Related if needed
  • Then do {{with $sortedRelated.Next . }}{{.RelPermalink}}{{end}} etc.

The collection of related pages excludes the current page. If you want to use the .Next and .Prev page methods, you must (a) append the current page to the collection of related pages, and (b) explicitly sort the resulting collection.

{{ $r := .Site.RegularPages.Related . | append . }}
{{ $r = sort $r "Date" "desc" }}

{{ with ($r.Prev .) }}
  <a href="{{ .RelPermalink }}">Previous Related Page</a>
{{ end }}

{{ with ($r.Next .) }}
  <a href="{{ .RelPermalink }}">Next Related Page</a>
{{ end }}

This is better.

3 Likes

Using the ByDate method should be faster (as the result is cached), e.g.:

`{{ $r = $r.ByDate.Reverse }}`
2 Likes