Search code examples
phparraystwig

how to convert array chunk in twig


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

Solution

  • 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 #}
        {% endif %}
    {% endfor %}
    

    documentation