How to list articles by month with Twig
Feb 21, 2020
Speaking of doing some maintenance to the blog, for months I had been trying to automate the way the Archive page of the website worked by making it populate itself automatically as pages were added to the blog, with no success.
The only thing I wanted to use was Twig, the flexible, fast, and secure template engine for PHP provided by Symfony many CMS's are based upon. My idea was to use a loop
function to call out months and print articles that had a date equal to that month. As it turned out, it was a bunch of work: first I stumbled upon some date_modify
bugs that actually were tied back to PHP's DateTime
function; and even after fixing that, I could not set out a way to make the if
condition work well enough to only print out months during which I actually had written something in.
It was an enriching process: I got to play around with coding and needed to learn many things along the way, but, in the end, all I wanted was not to manually type in entries every time I published something, so I asked. And help, once again, arrived.
Posting the question to Pico's GitHub Issues section, promptly yielded an answer from Pico's main developer:
{% set current_month = "" %}
{% for page in pages|sort_by("time")|reverse if page.time and not page.meta.unlisted %}
{% if page.time|date("Y-m") != current_month %}
{% set current_month = page.time|date("Y-m") %}
<h2>{{ page.time|date("F 'y") }}</h2>
{% endif %}
<a href="{{ page.url }}" title="{{ page.meta.description }}">{{ page.title }}</a><br>
{% endfor %}
The solution he came up with is nicer and more compact than the one I was chasing and, besides some Pico's specific functions, it should work somewhere else too.
I am posting it for future reference: I couldn't find it anywhere else and it has benefitted me greatly since implementing it about 20 days ago.
* * *
If you like articles like this, please consider supporting this website through personal donations or sponsorships