Setting element of array from Twig

falinsky picture falinsky · Feb 24, 2012 · Viewed 122.7k times · Source

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 ...

Answer

Paul picture Paul · Feb 24, 2012

There is no nice way to do this in Twig. It is, however, possible by using the merge filter:

{% set arr = arr|merge({'element': 'value'}) %}