Passing an array to an include in twig

Romainpetit picture Romainpetit · Nov 18, 2015 · Viewed 9.5k times · Source

Seems like the argument is not passed properly ...

    {% set items = {
        item: {
            'id': '1',
            'brand': 'client1',
            'description': 'solutions.client1.description' | trans},
        item: {
            'id':  '2',
            'brand': 'client2',
            'description': 'solutions.client2.description' | trans}
    } %}

    {% include 'site/case-excerpt.html.twig'
        with {'id': items.item.id,
              'brand': items.item.brand,
              'description': items.item.description
        }
  %}

Then in the site/case-excerpt.html.twig file :

{% include 'site/testimonials/item.html.twig'
     with {'id': id,
           'brand': brand,
           'description': description
          }
%}

And in the site/testimonials/item.html.twig file:

<div class="carousel-item {{ id }}">
    <img src="images/brands/{{ brand }}.jpg">
    <p>
        {{ description }}
    </p>
</div>

The expected output would be the following :

<div class="carousel-item 1">
    <img src="images/brands/client1.jpg">
    <p>
        I'm the content of the translation for the first client
    </p>
</div>
<div class="carousel-item 2">
    <img src="images/brands/client2.jpg">
    <p>
        I'm the content of the translation for the second client
    </p>
</div>

I dropped the idea of looping manually trough items since it seems to be possible to have it done nicely, here for example.

Answer

Mazzy picture Mazzy · Nov 18, 2015

In the example you provided, they loop through the objects, and include a partial for every object.

You are using items.item. Twig has no clue what you want, also, creating an array with the same key item, won't work

{% set items = [{
            'id': '1',
            'brand': 'client1',
            'description': 'solutions.client1.description' | trans},
            {
            'id':  '2',
            'brand': 'client2',
            'description': 'solutions.client2.description' | trans}
    ] %}

then loop through your items and include the partial

{% for item in items %}
    {% include 'site/case-excerpt.html.twig'
            with {'id': item.id,
                  'brand': item.brand,
                  'description': item.description
            }
{% endfor %}