3

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>

  • 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 '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 0:59
9

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 %}
  • I actually like Micahel's answer the best as there is no extra variables needed. – Siebird Jan 12 '15 at 14:50
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>
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, am I wrong or is date a string, not a DateTime object? – Paul Jan 9 '15 at 18:06
  • It is. I noticed it as soon as I posted and fixed it. Thanks – Douglas McDonald Jan 9 '15 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 '15 at 18:19
  • You're right Paul! Remind me never to answer questions before my first cup of coffee please. – Douglas McDonald Jan 9 '15 at 18:33
  • Coffee? Just finishing my first glass of whisky ;) – Paul Jan 9 '15 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.