Evans Evans - 3 months ago 34
Twig Question

Twig embed block not working when its within a loop?

I need to place a twig template into my page and place another twig template inside it.

In page.twig:

{% embed "parent.twig" %}
{% block something %}
{% include "child.twig" %}
{% endblock %}
{% endembed %}


In parent.twig:

{% set array = ['', '', '']
%}
<div class="parent">
{% for i in array %}
<div class="parent__item">
{% block cardBoard %}
{% endblock %}
</div>
{% endfor %}
</div>


The problem is that the block doesn't work when its within a loop. I can edit page.twig all I like but I would rather not change parent.twig if possible as its consumed by other applications.

Answer

Why do you put a block inside a for loop ? You can't have 2 blocks defined with the same name. In your case it will try to put this in your template 3 times :

  <div class="parent__item">
    {% block cardBoard %}
    {% endblock %}
  </div>

This will create a 500 server error : The block 'cardBoard' has already been defined line '' in :parent.twig at line ''.

If you really want to have content depending on the values in your array, put the block opening and closing outside the for loop. Like this for example :

{% set array  = ['', '', '']%}
<div class="parent__item">
    {% block cardBoards %}
       {% for i in array %}
           <div class="cardBoard{{ i }}>
           </div>
       {% endfor %}
    {% endblock %}
</div>
Comments