Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group posts by date on home page in Jekyll?

In Jekyll, I would like my home page to list the most recent posts grouped by date, like so:

September 6, 2013

  • Post 1
  • Post 2
  • Post 3

September 5, 2013

  • Post 1
  • Post 2

Basically, I just want to spit out a date heading when a post in the loop is from a different date from the one previously processed. I've tried to do this by testing if the next post in the for loop matches the date of the last post, and to display a date header only if it doesn't. This is what my Liquid template looks like:

---
layout: default
title: Home Page
---

{% assign thedate = '' %}

{% for post in site.posts %}

    {% if thedate != post.date | date: "%m-%d-%Y" %}
        <h2>{{ post.date | date: "%A, %B %e, %Y" }}</h2>
    {% endif %}

    {% assign thedate = post.date | date: "%m-%d-%Y" %}

    <h3 class="headline"><a href="{{ post.url }}">{{ post.title }}</a></h3>
    {{ post.content }}
    <hr>

{% endfor %}

If instead of using post.date | date: "%m-%d-%Y" I instead say simply post.date it works, and posts are grouped together, but only if the posts have the exact same date and time (not just the same day of the month). That's why I add the more specific post.date | date: "%m-%d-%Y".

Any ideas? Thanks so much for our help!!

like image 907
jerrybrito Avatar asked Sep 07 '13 02:09

jerrybrito


1 Answers

Found the answer by modifying the archives solution here: http://www.mitsake.net/2012/04/archives-in-jekyll/

Here is the code that works:

layout: default
title: Home Page
---

{% for post in site.posts %}

    {% capture day %}{{ post.date | date: '%m%d%Y' }}{% endcapture %}
    {% capture nday %}{{ post.next.date | date: '%m%d%Y' }}{% endcapture %}

    {% if day != nday %}
        <h5 class="date">{{ post.date | date: "%A, %B %e, %Y" }}</h5>
    {% endif %}
    {{ post.content }}
    <hr>

{% endfor %}
like image 169
jerrybrito Avatar answered Sep 28 '22 08:09

jerrybrito