从 Twig 设置数组元素数组、元素、Twig

2023-09-07 09:37:55 作者:奈何桥被强拆了

How can I set member of an already existing array from Twig?

I tried doing it next way:

{% set arr['element'] = 'value' %}
labview数组里的部分元素的平均值

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