Creating an array within for loop with Twig

前端 未结 2 1784
醉梦人生
醉梦人生 2021-02-14 23:21

I\'m trying to create an array and store values in it within for loop but failed so far. How can I do it with Twig?

I\'ve read these but being new in Twig makes it hard

2条回答
  •  庸人自扰
    2021-02-15 00:09

    I have other solution for arrays in loop. This solution is letting you to make arrays like PHP:

    $my_array[] = array('key_1' => $value1, 'key_2' => $value_2);
    

    in this case:

    {% set cars_details = [] %}
    {% for car in cars %}
         
        {% set car = car|merge({(loop.index0) : {'color': car.color, 'year': car.year} }) %}
    {% endfor %}
    {{ car|dump }}
    

提交回复
热议问题