I want to convert the following line from PHP to twig I tried many methods but no use can anyone guide me how to do...
<?php foreach (array_chunk($images, 4) as $image) { ?>
and
<?php if ($image['type'] == 'image') { ?>
The batch filter splits the original array into a number of chunks. Check out this example for better clarification:
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{#The first param to batch() is the size of the batch#}
{#The 2nd param is the text to display for missing items#}
{% for row in items|batch(3, 'No item') %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
This would be rendered as:
<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>
Reference
array_chunk
is built-in twig
as the slice
-filter
{% for image in images|slice(0,4) %}
{% if image.type == 'image' %}
{# I am an image #}
{% endif %}
{% endfor %}
You can shorten above example by moving the if
inside the for-loop
{% for image in images|slice(0,4) if image.type == 'image' %}
{# I am an image #}
{% endfor %}
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