On the list-all-posts page on this blog I wanted to group posts by year and show the year as a section-heading.
I found a StackOverflow answer that suggested using the group_by_exp
filter in Liquid. I used it as follows:
{% assign postsByYear = site.posts | group_by_exp:"post", "post.date | date: '%Y'" %}
{% for year in postsByYear %}
<h2>{{ year.name }}</h2>
<div class="post-list">
{% for post in year.items %}
<p>
<a href="{{ post.url }}" class="post-title">{{ post.title }}</a>
<br>
<span class="post-description">{{ post.summary }}</span>
</p>
{% endfor %}
</div>
{% endfor %}
If you want to further do sub-sections by month then you can use something like this:
{% assign postsByYear = site.posts | group_by_exp:"post", "post.date | date: '%Y'" %}
{% for year in postsByYear %}
<h2>{{ year.name }}</h2>
<div class="month-list">
{% assign postsByMonth = year.items | group_by_exp:"post", "post.date | date: '%B'" %}
{% for month in postsByMonth %}
<h3>{{ month.name }}</h3>
<div class="post-list">
{% for post in month.items %}
<p>
<a href="{{ post.url }}" class="post-title">{{ post.title }}</a>
<br>
<span class="post-description">{{ post.summary }}</span>
</p>
{% endfor %}
</div>
{% endfor %}
</div>
{% endfor %}