Having issues trying to access the year & month variable when grouping entries by month-year. The code is outputting the desired results (ie. December 2014), however I would like to format the url by 'year/month'.


Browse news & articles for the last year.

{% set allEntries = craft.entries.section('news').limit(null) %}
{% for date, entries in allEntries | group('postDate|date("F Y")') %}
    <li><a href="{{ year }}/{{ month }}">{{ date }}</a></li>
{% endfor %}

  • Both answers give me the desired results. Now I'm wondering what is the better answer? Paul's splits the date variable and Douglas use the DateTime object
    – Siebird
    Jan 9, 2015 at 18:16
  • Douglass is on the right track. You can get a DateTime to [re]format if you your year-month variable is in a format the date filter recognizes. I added a code snippet that I hope illustrates this helpfully. Jan 10, 2015 at 0:59

3 Answers 3


If I understand your example correctly, a simple hyphen would do the trick — "YYYY-MM" is a format the date filter recognizes.

{% set entries = ... %}
{% set entriesByMonth = entries|group('postDate|date("Y-m")') %}
{% for month, entries in entriesByMonth %}
      <a href="{{ month|date("Y") }}/{{ month|date("m") }}">
        {{ entries | length }} entries in {{ month|date("F Y") }}
{% endfor %}
  • I actually like Micahel's answer the best as there is no extra variables needed.
    – Siebird
    Jan 12, 2015 at 14:50

The year and month variables are not defined, so you'd first have to get these from the 'date' variable.

You could do this by using Twig's split function and splitting date by the space in between:

{% set dateParts = date | split(' ') %}
{% set month = dateParts[1] %}
{% set year = dateParts[0] %}

<a href="{{ year }}/{{ month }}">{{ date }}</a>

I was going to suggest using twig's date filter to format the date as needed, but as Paul astutely pointed out in his comment, you don't really have a dateTime variable to work with.

So my answer is use Paul's answer. ;)

  • Douglas, am I wrong or is date a string, not a DateTime object?
    – Paul
    Jan 9, 2015 at 18:06
  • It is. I noticed it as soon as I posted and fixed it. Thanks Jan 9, 2015 at 18:16
  • Douglas, this wouldn't work. Your entry variable now contains all entries, so you wouldn't be able to get a postDate from it ;)
    – Paul
    Jan 9, 2015 at 18:19
  • You're right Paul! Remind me never to answer questions before my first cup of coffee please. Jan 9, 2015 at 18:33
  • Coffee? Just finishing my first glass of whisky ;)
    – Paul
    Jan 9, 2015 at 18:34

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.