Setting element of array from Twig

前端 未结 10 779
北恋
北恋 2020-12-04 09:55

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

I tried doing it next way:

{% set arr[\'element\'] = \'value\' %}

but

10条回答
  •  再見小時候
    2020-12-04 10:46

    Just use this like {% set arr={'key':'value'} %} (with no blank space after the :), it works well.

    But when I use it inside a for loop, to make it an array, it does not work outside of the for scope.

    {% for group in user.groups %}
      {% set foo={'loop.index0':'group.id'} %}
      {% set title={'loop.index0':'group.title'} %}
      {{ title }} //it work 
    {% else %}
      {% set foo={'0':'-1'} %}
      {% set title={'0':'未分组'} %}
    {% endfor %}
    {{ title }}  //it does not work, saying title is not defined
    

提交回复
热议问题