5

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.

9
{% 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! – megkadams Jul 6 '15 at 16:40
  • Glad it helped! That group filter is powerful and mysterious. – Marion Newlevant Jul 7 '15 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.