Setting element of array from Twig

Solution 1:

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

Solution 2:

I ran into this problem but was trying to create integer indexes instead of associative index like 'element'.

You need to protect your index key with () using the merge filter as well:

{% set arr = arr|merge({ (loop.index0): 'value'}) %} 

You can now add custom index key like ('element'~loop.index0)

Solution 3:

If initialization only need:

{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}

Solution 4:

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