Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig: for each month of the Year

Tags:

twig

This is strange. If I use {{ j }}, I get all 12 numbers, but adding the Twig date filter just echos out "Jan" twelve times.

How do I echo out all months of the year? Do I have a create an array instead?

<select>
{% for j in range(1, 12) %}
    <option>{{ j|date('M') }}</option>
{% endfor %}
</select>
like image 938
Adam Elsodaney Avatar asked Sep 18 '12 12:09

Adam Elsodaney


1 Answers

It's because twig treats j as number of seconds from January 1970 (so it's always January).

From twig documentation:

The date filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, or DateInterval instances.

This should work:

{% for j in range(1, 12) %}
    <option>{{ date('2012-' ~ j ~ '-01') |date('M') }}</option>
{% endfor %}
like image 106
Cyprian Avatar answered Nov 23 '22 18:11

Cyprian