I’m trying to create a chronological archive of blog posts that looks like this:
2024
November
[Post Title] [day of month]
[Post Title] [day of month]January
[Post Title] [day of month]
[Post Title] [day of month]
Each year should be an h3 heading, each month an h4 heading, and posts are listed underneath with their day number. The posts are in descending order (newest first).
I can get the posts to display correctly with this:
{{#get "posts" limit="all" order="published_at desc"}}
{{#foreach posts}}
<li><a href="{{url}}">{{title}}</a> {{date published_at format="D"}}</li>
{{/foreach}}
{{/get}}
But when I try to add the year/month grouping logic, only the first year/month headers appear, while subsequent headers don’t show up (though the posts and their day numbers do). Here’s one of the many ways I’ve tried so far:
{{!-- Archive/Blogroll Section --}}
<section class="blogroll">
<h2>Archive</h2>
{{#get "posts" limit="all" order="published_at desc"}}
{{#foreach posts}}
{{#if @first}}
<h3>{{date published_at format="YYYY"}}</h3>
<h4>{{date published_at format="MMMM"}}</h4>
<ul>
{{else}}
{{#unless (match (date published_at format="YYYY-MM") (date ../posts.[0].published_at format="YYYY-MM"))}}
</ul>
<h3>{{date published_at format="YYYY"}}</h3>
<h4>{{date published_at format="MMMM"}}</h4>
<ul>
{{/unless}}
{{/if}}
<li>
<a href="{{url}}">{{title}}</a> {{date published_at format="D"}}
</li>
{{/foreach}}
</ul>
{{/get}}
</section>
I need help figuring out the correct logic to show new year/month headers whenever they change in the loop. The tricky part seems to be detecting when to insert new headers as we move through the posts. Does anyone have any ideas? Thanks.
- What version of Ghost are you using? GhostPro latest