JamesNZ
JamesNZ

Reputation: 512

Best way to output a list of months in a Twig template?

What is the best way to output a list of months in a Twig template? For example creating a month drop down in a date of birth set of fields. The format I am after is:

<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>

Upvotes: 3

Views: 3745

Answers (2)

malcolm
malcolm

Reputation: 5542

The form component actually do it, you just need to set format:

$builder->add('birth_date', DateType::class, ['format' => 'ddMMMMyyyy']);

The output is:

<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
...

Upvotes: 3

JamesNZ
JamesNZ

Reputation: 512

You can use a simple loop of 12 to create a date string for each month, then run that through Twig's date filter like below:

{% for month in 1..12 %}
    {% set date = month ~ "/1/2016" %}
    <option value="{{ date|date("m") }}">{{ date|date("F") }}</option>
{% endfor %}

This results in the requested format:

<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>

The format can easily be changed using php's date format options.

TwigFiddle of example here.

Upvotes: 6

Related Questions