Trying to create an archive page for each of my blog types within Craft. The page sorts by year and by month. (year and month are coming from my routes in this code.)

By using the following, I can print out each month with posts and the number of posts the month has. My problem is that I also need to print out the months with no post count and can't seem to figure out how to do that.

{% set entriesInYear = craft.entries.section('pressReleases').limit(null).after(year).before(year+1) %}

{% for month, entries in entriesInYear | group("postDate|date('F')") %}
    <li><a href="#">{{ month }}&nbsp;({{ entries|length }})</a></li>
{% endfor %}

That will yield me a printout of:

  • April (7)
  • March (4)
  • February (1)

I just need to also print out all the months in between with a (0) indicator.

1 Answer 1

{% set groupedEntries = entriesInYear | group("postDate|date('F')") %}

Will give you an associative array where the keys are the months, and the values are the entries for that month.

Now you need to loop over all the months, not just the ones in the groupedEntries.

Make an array of all the months.

{% set allTheMonths = ['January', 'February', 'March', ... 'December'] %}

Make an array of all the months that have entries (twig's keys filter)

{% set monthsWithEntries = groupedEntries | keys %}

Loop over the months (all of them), and output either the number of entries (groupedEntries[month]|length) or 0

{% for month in allTheMonths %}
  {% if month in monthsWithEntries %}
    <li><a href="#">{{ month }}&nbsp;({{ groupedEntries[month]|length }})</a></li>
  {% else %}
    <li><a href="#">{{ month }}&nbsp;(0)</a></li>
  {% endif %}
{% endfor %}
  • Amazing! And such a wonderful explanation, thank you SO much!
    – user3842
    Commented Jul 6, 2015 at 16:40
  • Glad it helped! That group filter is powerful and mysterious. Commented Jul 7, 2015 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.