Ian Ebden
Ian Ebden

Reputation: 111

Output list of next 6 months in Twig

I'm trying to output a dropdown menu of the next 6 months but having no luck. I know I'm doing something stupid here. Can anyone help out? Here's where I'm at:

<select>
  <option value="">This month</option>
    {% for i in range(1, 6) %}
      <option value="">
        {{ now.date|date_modify("+" ~ i ~ " month")|date('F Y') }}
      </option>
    {% endfor %}
</select>

Upvotes: 0

Views: 637

Answers (1)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

There's a helpful comment on PHP's strtotime documentation page:

WARNING when using "next month", "last month", "+1 month", "-1 month" or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.

...

(Source: https://secure.php.net/manual/en/function.strtotime.php#107331)

So you should use first day of +i month instead of +i month:

<select>
  <option value="">This month</option>
    {% for i in 1..6 %}
      <option value="">
        {{ "now"|date_modify("first day of +" ~ i ~ " month")|date('F Y') }}
      </option>
    {% endfor %}
</select>

Notice that I changed now.date to "now", as pointed out by @DarkBee. I also used for i in 1..6 instead of the range function; the 1..6 is just syntactic sugar as described in the documentation of the range function.

Upvotes: 1

Related Questions