Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array within for loop with Twig

Tags:

twig

symfony

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 to convert into my case.

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

PLAIN PHP LOGIC IS THIS:

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

foreach ($new_array as &$v)
{
   echo $v;
}

WHAT I'VE TRIED WITH TWIG:

{% for value in array %}
    {% set new_array = new_array|merge([value])  %}
{% endfor %}

{% for v in new_array %}
   {{ v }}
{% endfor %}
like image 289
BentCoder Avatar asked Jun 04 '14 17:06

BentCoder


People also ask

How do you access an array in twig?

Accessing array elements Twig as a parameter can receive array. To access a specific element of array you can use regular php array access bracket notation {{ array[key] }} .

What is Loop index0?

loop.index0. The current iteration of the loop. This variable starts counting at 0. loop.last. This variable evaluates to true, if it is the last iteration of the loop.


2 Answers

Solved by following Vision's suggestion:

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

{% for brand in brands %}
   {{ brand }}
{% endfor %}

Also I'll take bartek's comment into consideration next time. This was one off.

like image 148
BentCoder Avatar answered Oct 27 '22 11:10

BentCoder


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 %}
     <!-- 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 }}
like image 32
bumerang Avatar answered Oct 27 '22 13:10

bumerang