Search code examples
phphtmltwigtemplate-engine

Does Twig have equivalent 'append'?


{% block page %}
   <ul class="gallery">
     {% set foo = 0 %}
     {% for products in prodArr %}
       {% if foo % 4 == 0 %}
         <ul class="slides">
           <li>Product</li>
         </ul>
       {% else %}
         <li>Another Product<li> // this
       {% endif %}
     {% set foo = foo + 1 %}
     {% endfor %}
   </ul>
{% endblock %}

In other case I want that li will append to ul with class slides. Is this possible?

I want that my HTML will be look like this:

<ul class="gallery">
  <ul class="slides">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
  <ul class="slides">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</ul>

Solution

  • Twig has embed and include, but in your case you can just refactor your code like this:

    // UPDATED:
    <ul class="gallery">
        {% for chunk in products|batch(4) %}
            <ul class="slides">
                {% for product in chunk %}
                    <li>{{ product.title }}</li> // assuming you have title property
                {% endfor %}
            </ul>
        {% endfor %}
    </ul>
    

    P.S. Unfortunately I can not test it but you will get the general idea ;)