Foreach Loop with Multiple Elements in the Twig Template Engine

I use Twig as a template for my PHP web application.

I would like to know if there is a quick way to get many elements in a foreach block.

This is my data:

users=>[
 ["name"=>"User1"],
 ["name"=>"User2"],
 ["name"=>"User3"],
 ["name"=>"User4"],
 ["name"=>"User5"],
 ["name"=>"User6"]
]

This will be a standard loop (each element):

<ul>
    {% for user in users %}
        <li>{{ user.name }}</li>
    {% endfor %}
</ul>

But this is what I need in the element block n (in this example n = 3 )

<ul>
    <li>User1</li>
    <li>User2</li>
    <li>User3</li>
</ul>
<ul>
    <li>User4</li>
    <li>User5</li>
    <li>User6</li>
</ul>

Is there a quick way to do this in Twig, or do I need to prepare the data differently with another level of submachine?

+4
source share
1 answer

It looks like you need to use a filter batch:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

It will display:

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</td>
        <td>e</td>
        <td>f</td>
    </tr>
    <tr>
        <td>g</td>
        <td>No item</td>
        <td>No item</td>
    </tr>
</table>

Source: Twig Documentation

+7
source

All Articles