Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert array chunk in twig

Tags:

arrays

php

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') { ?>
like image 250
Muhammed Avatar asked Dec 05 '22 14:12

Muhammed


2 Answers

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

like image 70
Niket Pathak Avatar answered Dec 24 '22 07:12

Niket Pathak


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

like image 38
DarkBee Avatar answered Dec 24 '22 09:12

DarkBee