Grouping blog posts by year

Highlighted
New Contributor

I'm looking to create a blog template that functions in the same way to this page: https://www.familyzone.com/news

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.

Reply
0 Upvotes
3 Replies
Community Manager

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

 

@dennis_e@AntonB@MitchL do you have any suggestions for @katiesutcliffe?

 

Thanks,
Jenny


Did my post help answer your query? Help the Community by marking it as a solution
Reply
0 Upvotes
Occasional Contributor

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? 

Reply
0 Upvotes
Advisor | Platinum Partner

@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. 

dennis
Reply
0 Upvotes