Group posts by year in Eleventy
When looking for a way to group my blog posts by year, I've found two approaches:
- By going procedurally through all posts and adding a new headline when the year changes.
- By creating one collection per year.
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.
- 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.
- 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 %}