Grouping blog posts by year

I’m looking to create a blog template that functions in the same way to this page: Family Zone | Qustodio

With blogs grouped into months grouped into years.

The issue is the news page uses a HubDB in the backend, so it functions a little differently to blogs, and I’m having a huge amount of trouble getting blog posts to group together by year.

I can print the publish year with

{% for post in all_posts %}

{% set post_year = post.publish_date_local_time|datetimeformat('%Y') %}

{{ post_year }}

{% endfor %}

I’ve tried grouping them with

{% set yearGroup = posts|groupby(publish_date_local_time|truncate(4)) %}

and

{% set yearGroup = posts|groupby(post_year) %}

But it’s obviously the wrong approach.

@katiesutcliffe I want to tag some subject matter experts into the conversation:

@dennisedson, @AntonB, @MitchL do you have any suggestions for @katiesutcliffe?

Thanks,
Jenny

Hey @katiesutcliffe,

I’m unable to view the familyzone page you’re referring to - its asking me for a password. Could you provide a screenshot of the page?

@katiesutcliffe,

see if this works:

{% for content in contents %}
 {% set year = content.publish_date|datetimeformat('%Y') %}
 {% set month = content.publish_date|datetimeformat('%B') %}
 {% if loop.index = 0 %}
 <h2>
 {{ year }}
 </h2>
 <h3>
 {{ month }} 
 </h3>
 {% endif %}
 {% if year != nextYear %}
 <h2>
 {{ year }}
 </h2>
 {% endif %}
 {% if month != nextMonth %}
 <h3>
 {{ month }}
 </h3>
 {% endif %}
 <div>
 {{ content.name }}
 </div>
 {% set nextYear = content.publish_date|datetimeformat('%Y') %}
 {% set nextMonth = content.publish_date|datetimeformat('%B') %}

{% endfor %}

add whatever you need for the item in the div with content name.

@katiesutcliffe,

i built a working demo of the functionality here

@dennisedson Thanks so much! Beautiful solution.