Group by year/time order

When crafting an archive page I wanted to group the posts based on the post date year (without pagination). This is what I tried…

for year, posts in section.pages | group_by(attribute="year")

But I also wanted the year to be in descending order while the posts (per year) be in ascending order.

I didn’t find any way of doing this. Is there one?

I figured out how to do this, but it’s a little fiddly.

{% set year = "-1" %}
{% for page in paginator.pages %}
  {% set this_year = page.date | date(format="%Y") %}
  {% if year != this_year %}
    {% set_global year = this_year %}
    <li class="year"><h2>{{ year }}</h2></li>
  {% endif %}
  <li>
    <a href="{{ page.permalink | safe }}"><aside class="dates">{{ page.date | date(format="%b %d") }}</aside></a>
    <a href="{{ page.permalink | safe }}">{{ page.title }}<h2>{{ page.description }}</h2></a>
  </li>
{% endfor %}

In a ul it will create a header li for each grouping.

EDIT: Additionally, for ordering, you can control the order in the _index.md file’s frontmatter:

+++
sort_by = "date"
+++

If you want to control the order, you may have to use the Tera reverse filter, though I’m not sure if that works in this case.

1 Like

It feels a bit like a workaround - but I guess that should do it.
Thanks a lot, @mysteriouspants.