Conditionally sorting a list of pages

I’m trying to sort a collection of pages that I have in this form:

{{ range .context.Pages }}
  {{ .Title }}
{{ end }}

I would like this list to be iterated by reverse date only in a certain section of the site (e.g. the section ‘releases’).

I could create two partials, but I’m trying to learn a way that would have a conditional statement on this one, allowing to alter the .context.Pages fed to range in a way that’s self-contained to this partial, or even to the range block itself if possible.

{{ $pages := .context.Pages }}
{{ if eq page.Section "releases" }}
  {{ $pages = sort $pages "Date' "desc" }}
{{ end }}
{{ range $pages }}
  ...
{{ end }}

I haven’t tested it, there may be typo.

References:

1 Like

A small note (for any newbie like me) is that the first line needs to be a declaration with assignment, hence := instead of =. The rest is exactly the type of example I was looking for.

Thank you!

1 Like

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