4

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'.

Archives

Browse news & articles for the last year.

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

Siebird
  • 373
  • 1
  • 11
  • 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 09 '15 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. – Michael Rog Jan 10 '15 at 00:59

3 Answers3

10

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 %}
  <li>
      <a href="{{ month|date("Y") }}/{{ month|date("m") }}">
        {{ entries | length }} entries in {{ month|date("F Y") }}
      </a>
  </li>
{% endfor %}
Michael Rog
  • 3,420
  • 1
  • 18
  • 27
4

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>
Paul
  • 6,338
  • 12
  • 26
1

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 McDonald
  • 13,457
  • 24
  • 57