Darek Kay's picture
Darek Kay
Solving web mysteries

Group posts by year in Eleventy

When looking for a way to group my blog posts by year, I've found two approaches:

Both solutions didn't feel optimal, so I came up with a third variant. This method uses a single 11ty collection consisting of [year, posts] tuples.

  1. Define a custom collection in .eleventy.js:
const _ = require("lodash");

eleventyConfig.addCollection("postsByYear", (collection) => {
  return _.chain(collection.getAllSorted())
    .groupBy((post) => post.date.getFullYear())
    .toPairs()
    .reverse()
    .value();
});

I'm using lodash to group all posts by year, transform the object into an array and reverse the result (descending order). This method can be used to group posts by any other property, e.g. category.

  1. Render the posts with Nunjucks:
{% for year, yearPosts in collections.postsByYear %}
  <h2>{{ year }}</h2>
  <ul>
    {% for post in yearPosts | reverse %}
      <li>{{ post.data.title }}</li>
    {% endfor %}
  </ul>
{% endfor %}

Check out my blog index to see the final result.


Related posts

Group posts by year in Eleventy