Nithin Bekal About

Jekyll: Group posts by year

16 Jul 2023

Recently, I changed the layout of the home page of this blog to group posts by year rather than having one long list of posts. I had to spend some time looking this up, but it turns out Jekyll has a way to group an array by using an expression.

{% assign years = site.posts
   | group_by_exp: "post", "post.date | date: '%Y'"
%}

Now you can use this grouped array to iterate over years like this:

{% for year in years %}
  <p>{{ year.name }}</p>

  <ul>
    {% for post in year.items %}
      <li>
        <a class='title' href='{{ post.url }}'>{{ post.title }}</a>
      </li>
    {% endfor %}
  </ul>
{% endfor %} 

Here’s a screenshot of the home page of this blog with the new and old versions:

Jekyll posts grouped by year

Hi, I’m Nithin! This is my blog about programming. Ruby is my programming language of choice and the topic of most of my articles here, but I occasionally also write about Elixir, and sometimes about the books I read. You can use the atom feed if you wish to subscribe to this blog or follow me on Mastodon.