For in twig with include

3.6k views Asked by At

I need do a cycle for with an include directive in twig but the template twig will not repeat. This is a snippet of my code:

...
{% for object in objects %}
   {% include 'template.html.twig' with {'object':object} %}
{% endfor %}
...

Only the first object is received, but the rest of the objects I need are not received.

2

There are 2 answers

1
Dasaaf On BEST ANSWER

The problem had nothing to do with TWIG, the error was in JQUERY. The FOR-LOOP is valid with an INCLUDE inside.

TEMPLATE TWIG 1: print n modals with different contents

...
{% for object in objects %}
   {% include 'template2.html.twig' with {'object':object} %}
   <button type="button" class="btn-primary" title="modal-view" data-toggle="modal" data-target="#modal-{{object['id_object']}}">View</button>
{% endfor %}
...

TEMPLATE TWIG 2: modal bootstrap

...
<div id="modal-{{object['id_object']}}" class="modal fade" role="dialog">
   <div class="modal-dialog">
        <div class="modal-content">
             <div class="modal-header">
                 <h2 class="modal-title">{{object['title']}}</h2>
             </div>
             <div class="modal-body">
                 <p>{{object['content']}}</p>
             </div>
        </div>
   </div>
</div>
...
1
Alvin Bunk On

I haven't tried anything like that before, but I wonder if this might work or not:

{% include 'template.html.twig' with {'objects':objects} %}

In order words don't put that in the for loop, and pass objects directly to your included template, and then within the template.html.twig you can also use the objects array directly.

Again, I'm not sure if this will work; maybe you can try it, or maybe you need something different.