Eleventy: How do you list all posts grouped by year?

Created on 24 Jun 2020  路  2Comments  路  Source: 11ty/eleventy

I am using the Eleventy-base-blog and on the archive page it lists all the posts in chronological order.
This is the folder structure. All 2010 .md files are in the /posts/2010/ folder. And so on...

/posts/2010/
/posts/2011/
/posts/2012/
.....

The archived page works perfectly however, I want to group all 2010 posts together under the heading 2010. Then, all 2011 posts under 2011.....any idea how to achieve this or point me in the right direction?

Thanks!

education

Most helpful comment

It works and I think I got this one with some nunjucks code :)
So, in my postlist.njk I wrote this:

<ol reversed>
{% set currentYear = "" %}
{% for post in postslist | reverse %}
{% if showYear %}
      {% set postYear = post.date.getFullYear() %}
      {% if currentYear != postYear %}
      {% set currentYear = postYear %}
      <h3>{{ postYear }}</h3>
      {% endif %}
{% endif %}
  <li class=" mb-10 list-none">
    <h2><a href="{{ post.url | url }}">{% if post.data.title %}{{ post.data.title }}{% else %}<code>{{ post.url }}</code>{% endif %}</a></h2>
  </li>
{% endfor %}
</ol>

And, in the archive.njk file I have this:

<h1>Blog</h1>
{% set showYear = true %}
{% set postslist = collections.posts %}
{% include "postslist.njk" %}

The output is:

2012
Blog post 1
Blog post 2

2011
Blog post 1
Blog post 2

2010
Blog post 1
Blog post 2

This way, my index.njk which also lists the latest 10 posts won't show the date as I don't have the showYear.

Is this the best way to achieve this?

Thanks!

All 2 comments

It works and I think I got this one with some nunjucks code :)
So, in my postlist.njk I wrote this:

<ol reversed>
{% set currentYear = "" %}
{% for post in postslist | reverse %}
{% if showYear %}
      {% set postYear = post.date.getFullYear() %}
      {% if currentYear != postYear %}
      {% set currentYear = postYear %}
      <h3>{{ postYear }}</h3>
      {% endif %}
{% endif %}
  <li class=" mb-10 list-none">
    <h2><a href="{{ post.url | url }}">{% if post.data.title %}{{ post.data.title }}{% else %}<code>{{ post.url }}</code>{% endif %}</a></h2>
  </li>
{% endfor %}
</ol>

And, in the archive.njk file I have this:

<h1>Blog</h1>
{% set showYear = true %}
{% set postslist = collections.posts %}
{% include "postslist.njk" %}

The output is:

2012
Blog post 1
Blog post 2

2011
Blog post 1
Blog post 2

2010
Blog post 1
Blog post 2

This way, my index.njk which also lists the latest 10 posts won't show the date as I don't have the showYear.

Is this the best way to achieve this?

Thanks!

I don't know if it's the best way, but it solved my issue nicely. What's the correct way to get data to a layout so I can do a "groupby" on it? #15

Was this page helpful?
0 / 5 - 0 ratings