Adam Elsodaney
Adam Elsodaney

Reputation: 7808

Twig: for each month of the Year

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>

Upvotes: 6

Views: 11405

Answers (3)

devad
devad

Reputation: 13

For me:

{% for j in 1..12 %}
    <option>{{ '2012-' ~ j ~ '-01' |date('M') }}</option>
{% endfor %}

is working fine.

Upvotes: 0

Ravi
Ravi

Reputation: 93

The solution given by Cyprian Throwed me the following error

The function "date" does not exist

So I changed code to

{% for j in 1..12 %}
    <option>{{ j |date('2012-' ~ j ~ '-01') |date('M') }}</option>
{% endfor %}

and this worked for me.... Thanks Cyprian

Upvotes: 3

Cyprian
Cyprian

Reputation: 11374

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 %}

Upvotes: 23

Related Questions