I am new to Twig and looking for a solution for the following (which would be very easy in PHP, however, our templates are setup in Twig)
What I'm trying to do
Edit an array value (using its index) in Twig so that it can be output after a loop.
What is happening
The array value (retrieved using its index) does not change when I try to edit the array value by index. Instead, it may append the value to the array
My code
...
{% set amount = [0,0,0] %}
{% for invoice in invoices %}
<tr>
<td>{% if invoice.age <= 10 %}{% set amount ?????? %}{% endif %}</td>
<td>{% if invoice.age > 10 and invoice.age <= 20 %}{% set amount ?????? %}{% endif %}</td>
<td>{% if invoice.age > 20 %}{% set amount ?????? %}{% endif %}</td>
</tr>
{% endfor %}
...
{{ amount[0] }}
What I've tried
I have tried the following to change the value of age[0]
to no avail.
{% set amount = amount|merge({0: 'test'}) %}
{% set amount = amount|merge({0: 'test'})|keys %}
{% set amount = amount|merge({(0), 'test'}) %}
{% set amount = amount|merge({(0), 'test'})|keys %}
... and many more.
Intended outcome
I want to be able to output {{ age[0] }}
at the end to display the amount total of all invoices aged 10 or less. Similarly, I would also like to output age[1]
and age[2]
to display amount total for all invoices aged between 10 and 20 days, and over 20 days, respectively.