Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting element of array from Twig

Tags:

php

twig

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

like image 552
falinsky Avatar asked Feb 24 '12 14:02

falinsky


People also ask

How do you use variables in twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .


1 Answers

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'}) %} 

If element is a variable, surround it with brackets:

{% set arr = arr|merge({(element): 'value'}) %} 
like image 184
Paul Avatar answered Oct 12 '22 10:10

Paul