Design series – post list with months

Meanwhile, the number of posts is big enough to add the capability to jump to a specific month. Instead of trying it myself, I asked ChatGPT how to do it and used the resulting code with just a small modification. Impressive.

The change needed to be done in _layouts/home.html:

    {% assign previous_month = "" %}
    {% assign previous_year = "" %}
    
    <ul>
      {% for post in site.posts %}
        {% capture current_month %}{{ post.date | date: "%B" }}{% endcapture %}
        {% capture current_year %}{{ post.date | date: "%Y" }}{% endcapture %}
        {% if current_month != previous_month or current_year != previous_year %}
          <li><a href="#{{ current_month }}-{{ current_year }}">{{ current_month }} {{ current_year }}</a></li>
        {% endif %}
        {% assign previous_month = current_month %}
        {% assign previous_year = current_year %}
      {% endfor %}
    </ul>

    <ul class="post-list">
      {%- for post in site.posts -%}
      {% capture current_month %}{{ post.date | date: "%B" }}{% endcapture %}
      {% capture current_year %}{{ post.date | date: "%Y" }}{% endcapture %}

      {%- if current_month != previous_month or current_year != previous_year -%}
        {%- if previous_month != "" -%}
    </ul>
        {% endif %}
    <h2 id="{{ current_month }}-{{ current_year }}">{{ current_month }} {{ current_year }}</h2> 
    <ul class="post-list">
      {%- endif -%}

      <li>
        {%- assign date_format = site.minima.date_format | default: "%b %-d, %Y" -%}
        <span class="post-meta">{{ post.date | date: date_format }}</span>
        <p>
          <a class="post-link" href="{{ post.url | relative_url }}">
            {{ post.title | escape }}
          </a>
        </p>
        {%- if site.show_excerpts -%}
          {{ post.excerpt }}
        {%- endif -%}
      </li>

      {%- assign previous_month = current_month -%}
      {%- assign previous_year = current_year -%}

      {%- endfor -%}
    </ul>