从 Twig 设置数组元素

2022-01-22 00:00:00 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 ...

解决方案

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

相关文章