4

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') { ?>

2 Answers 2

15

Use Twig's built in batch() filter

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

3

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

2
  • I am new to twig so can you describe this in detail
    – Muhammed
    Jun 28, 2017 at 6:43
  • Which part? I've added a link to the slice documentation in the answer
    – DarkBee
    Jun 28, 2017 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.