New Zola Template For Archives Grouped By Year And Month
One of the GOTCHAs I ran into with moving to the new version of Zola is my archives have always been grouped by year and month. That always just worked in the past.
With the new version, when using group_by the order seems to have gotten mixed up.
They are in alpha so this may be fixed at some point. After several days I managed to find a way to get it working. This was one of my biggest hangups with the switchover.
I had to sort the maps before running the next for loop.
Here is the code below. Please excuse any messiness or cruft I left in there from experimenting. This can help you get the gist of how it’s done.
{%- block content -%}
{{- section.content | safe -}}
{%- set Years = [] -%}
{%- set Months = [] -%}
{#%- set Blog = get_section(path = "blog/_index.md") -%#}
{% for year, ignored in section.pages | group_by(attribute="year", ) %}
{% set_global Years = [...Years , year] %}
{% endfor %}
{%- set Years = Years | sort | reverse -%}
{%- set_global Archive = "" -%}
<details class="drop">
<summary>Years </summary>
<ul>
{%- for Year in Years -%}
<li><a href = "#{{- Year | safe -}}" title="Go to {{ Year | safe }}">{{- Year | safe -}}</a></li>
{%- endfor -%}
</ul> </details>
{%- for Year in Years -%}
{%- set_global Months = [] -%}
{% set_global ByYear = section.pages | filter(attribute="year", value=Year) -%}
<h2 id="{{- Year }}"><time datetime="{{- Year -}}">{{- Year -}}</time></h2>
{%- set_global ByMonth = ByYear | group_by(attribute = "month") -%}
{%- for Month, ignored in ByMonth -%}
{%- set_global Months = [...Months,Month] -%}
{%- endfor -%}
{%- set Months = Months | sort | reverse -%}
{%- for Month in Months %}
{%- set Month = Month | int %}
{%- if Month > 9 -%}
{%- set TheMonth = "2000-" ~ Month ~ "-10" %}
{%- else -%}
{%- set TheMonth = "2000-0" ~ Month ~ "-10" %}
{%- endif -%}
{%- set TheMonth = <DateML D={TheMonth}/> -%}
{%- set posts = ByMonth[Month] -%}
{%- if posts is defined -%}
<h3 >{{- TheMonth | safe -}}</h3><ul>
{%- for post in posts -%}
{%- set LongDate = <DateLong D={post.date} /> -%}
{%- set TheTitle = post.title | escape_html |safe -%}
<li><a href="{{- post.permalink | safe -}}" title ="{{- TheTitle | safe -}}">{{- TheTitle | safe -}}</a><time datetime="{{- post.date | safe -}}"> - {{ LongDate -}} </time></li>
{%- endfor %}
</ul>
{%- endif %}
<a href="#Top" title="back To Top" class="top">Top</a>
{%- endfor -%}
{%- endfor -%}
</article>
{{- super() -}}
{% endblock %}
Please don’t hesitate to use this if it will help you, and modify it as you need to make it work for your requirements.