Creating an array inside a loop with Twig

I am trying to create an array and store the values ​​in it inside a loop, but so far have failed. How can I do this using Twig?

I read them, but being new to Twig is hard to convert to my case.

  • Twig for loop and array with key
  • How to set array value in twig template
  • building a twig-building array for a loop
  • And much more

PLAIN PHP LOGIC THIS:

foreach ($array as &$value) { $new_array[] = $value; } foreach ($new_array as &$v) { echo $v; } 

WHAT I GOT WITH TWIG:

 {% for value in array %} {% set new_array = new_array|merge([value]) %} {% endfor %} {% for v in new_array %} {{ v }} {% endfor %} 
+7
symfony twig
source share
2 answers

It is solved as follows:

 {% set brands = [] %} {% for car in cars %} {% if car not in brands %} {% set brands = brands|merge([car]) %} {% endif %} {% endfor %} {% for brand in brands %} {{ brand }} {% endfor %} 

And next time I will take into account the comments of bartek. That was one thing.

+15
source share

I have another solution for arrays in a loop. This solution allows you to create arrays such as PHP:

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

in this case:

 {% set cars_details = [] %} {% for car in cars %} <!-- This is the line of code that does the magic --> {% set car = car|merge({(loop.index0) : {'color': car.color, 'year': car.year} }) %} {% endfor %} {{ car|dump }} 
0
source share

All Articles