PrimuS PrimuS - 1 month ago 13
PHP Question

Twig fill array with last 14 month

I want to fill an array with the last 14 month with twig.

I tried

{% for i in 14..0 %}
{% if i > 0 %}
{{ "now -"~i~" months"|date("M") }}<br/>
{% else %}
{{ "now"|date("M") }}* {{ i }}<br/>
{% endif %}
{% endfor %}


but that throws an error at this line
{{ "now -"~i~" months"|date("M") }}<br/>



Failed to parse time string ( months) at position 0 (m): The timezone could not be found in the database")


This works

{{ 'now -15 months'|date("M") }}


and dumping
i
gives me an integer (I think): enter image description here

Where am I wrong, is something like the above even possible?

Answer

You should surround with parentheses, as example:

{{ ("now -"~i~" months")|date("M") }}

So try this:

{% for i in 14..0 %}
    {% if i > 0 %}
        {{ "now"|date("M") }}* {{ i }}<br/>
    {% else %}
        {{ ("now -"~i~" months")|date("M") }}<br/>
    {% endif %}
{% endfor %}

Here a working example.

Hope this help