[SOLVED] Loop through subsection's posts

Thanks for your help!

I managed to get what I want, and pretty simply actually. I will explain it so it could help someone in the same situation. Tell me if you want a PR with this example in the Hugo Docs.

Let’s say we have a directory structure like in my first message. We want to list the subsection’s articles a) on the subsection _index and b) on each subsection article, and we want c) to navigate through them with previous and next links on each subsection article (navigation delimited to subsection).

a) we can list subsection’s articles on the _index with

{{ range .Data.Pages }}

easy, but if the same partial to display the list is shared between the _index and the article, as this code won’t work on the “single” article page we take care of wrapping it within

{{ if eq .File.BaseFileName "_index" }} ... {{ else }}

(for example)

b) to display the same list of subsection’s articles on each article we can set a subsection variable “subsection” in the front-matter of our articles and use

... {{ else }} {{ range where .Site.Pages "Params.subsection" .Params.subsection }}

to loop through pages and filter to get only the ones in subsection.

c) finally, the previous code is a good base to get our “in-subsection-previous” and “in-subsection-next” links :

{{ $currentPage := . }}
{{ range where .Site.Pages "Params.subsection" .Params.subsection}}
  {{ if eq .URL $currentPage.URL }}
    <li class="page-item{{ if ne .Prev.Params.subsection .Params.subsection }} disabled noselect{{ end }}"><a class="page-link" href="{{ .Prev.URL }}">précédent</a></li>
    <li class="page-item{{ if ne .Next.Params.subsection .Params.subsection }} disabled noselect{{ end }}"><a class="page-link" href="{{ .Next.URL }}">suivant</a></li>
  {{ end }}
{{ end }}

as you see the trick is to set the prev/next links only when the subsection variable of the prev/next article has the same value than the current article.

You can see the final code here. So far so good it works exactly as I expect, but if you see any way to do it more simply it would be great, for example to prevent having to use a different loop on the _index and on a single page, or to get the “in-subsection-prev/next” links through a built-in variable…

1 Like