Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop with multiple element in Twig template engine

I'm using Twig as template framework for my PHP web application.

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

This is my data:

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

This would be a standard loop (each item):

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

But this is what I need in block of n elements (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>

Exists a fast way to do this in Twig or should I prepare the data in a different way with a one more subarray layer?

like image 914
Tobia Avatar asked Mar 11 '15 09:03

Tobia


1 Answers

Looks like you need to use batch filter:

{% 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 render:

<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

like image 178
Rodin Vasiliy Avatar answered Sep 20 '22 15:09

Rodin Vasiliy