How can I set member of an already existing array from Twig?
I tried doing it next way:
{% set arr['element'] = 'value' %}
but I got the following error:
Unexpected token "punctuation" of value "[" ("end of statement block" expected) in ...
How can I set member of an already existing array from Twig?
I tried doing it next way:
{% set arr['element'] = 'value' %}
but I got the following error:
Unexpected token "punctuation" of value "[" ("end of statement block" expected) in ...
Thanks for this thread -- I was also able to create an array with (loop.index0) and send to twig.
There is no nice way to do this in Twig. It is, however, possible by using the merge filter:
I've found this issue very annoying, and my solution is perhaps orthodox and not inline with the Twig philosophy, but I developed the following:
that can be used as follows:
{% set arr = set_element(arr, 'element', 'value') %}
I ran into this problem but was trying to create integer indexes instead of associative index like 'element'.
You need to protect your index key with
()
using the merge filter as well:You can now add custom index key like
('element'~loop.index0)
I have tried @LivaX 's answer but it does not work , merging an array where keys are numeric wont work ( https://github.com/twigphp/Twig/issues/789 ).
That will work only when keys are strings
What I did is recreate another table (
temp
) from the initial table (t
) and make the keys a string , for example :t
keys : 0 , 1 , 2 ..temp
keys : 0_, 1_ , 2_ ....If initialization only need: