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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With