Foreach loop with multiple element in Twig template engine

Foreach loop with multiple element in Twig template engine

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Chunking Data in Twig Without PHP Preprocessing

When working with template engines like Twig, a common requirement arises when rendering data that needs to be split into fixed-size blocks. You have a flat array of items—say, a list of users—and you want to render them not as a single continuous stream, but grouped into chunks of n elements (e.g., three per list).

The straightforward approach is what most developers start with: iterating directly over the raw array and rendering each item inside a loop. However, this produces a single long list rather than multiple smaller lists. Achieving the desired output structure—multiple <ul> tags containing exactly n items each—requires either restructuring the data before it reaches the template or leveraging Twig's logic to handle the grouping.

Why Simple Loops Fail for Chunking

Consider your raw data structure:

$users = [
    ["name" => "User1"],
    ["name" => "User2"],
    ["name" => "User3"],
    ["name" => "User4"],
    ["name" => "User5"],
    ["name" => "User6"]
];

In Twig, a standard loop looks like this:

<ul>
    {% for user in users %}
        <li>{{ user.name }}</li>
    {% endfor %}
</ul>

This renders all six users in one list. To get multiple lists of three items each, the engine needs to know where to break the stream. Twig does not provide a built-in chunk filter that automatically splits an array into sub-arrays like some other languages or libraries might. Without a native chunking mechanism, you cannot simply write {% for chunk in users %} because Twig treats users as a flat sequence of dictionaries, not a sequence of sequences.

The Preprocessing Approach: Using PHP to Chunk Data

The most performant and reliable solution is to handle the grouping logic in your PHP controller or service layer before passing the data to the view. This keeps the template clean and delegates complex logic to where it belongs: the application layer.

You can use PHP's built-in array_chunk function to split the array into chunks of size three:

$chunkedUsers = array_chunk($users, 3);
// Result: [
//   [0] => [{"name"=>"User1"}, {"name"=>"User2"}, {"name"=>"User3"}],
//   [1] => [{"name"=>"User4"}, {"name"=>"User5"}, {"name"=>"User6"}]
// ]

Now, pass $chunkedUsers to your Twig template. Inside the template, you can iterate over these chunks and render each one within its own list:

<ul>
    {% for chunk in chunkedUsers %}
        <ul>
            {% for user in chunk %}
                <li>{{ user.name }}</li>
            {% endfor %}
        </ul>
    {% endfor %}
</ul>

This method is efficient because array_chunk runs once on the server, and Twig simply renders what it's given. It avoids unnecessary complexity in the template and ensures that even if your data source changes size, the chunking logic remains consistent.

Alternative: Using a Filter for Reusability

If you prefer to keep the chunking logic inside the template without modifying the controller, you can create a custom Twig filter or extension. This is useful when multiple templates need the same behavior and you want to avoid repeating PHP code in every view.

Define a filter in your AppServiceProvider:

use Illuminate\Support\Facades\Twig;

Twig::addFunction('chunk', function ($array, $size) {
    return array_chunk($array, $size);
});

Then use it directly in the template:

{% set chunkedUsers = users|chunk(3) %}

<ul>
    {% for chunk in chunkedUsers %}
        <ul>
            {% for user in chunk %}
                <li>{{ user.name }}</li>
            {% endfor %}
        </ul>
    {% endfor %}
</ul>

This approach keeps the template self-contained but still relies on PHP to perform the actual splitting. It's a good balance between separation of concerns and template flexibility.

Performance and Readability Trade-offs

There is no "fast way" in Twig alone to chunk arrays because the engine doesn't support it natively. The performance cost of array_chunk in PHP is negligible for typical application sizes, and moving this logic out of the loop prevents Twig from having to manage complex state internally.

Attempting to implement chunking purely in Twig using recursion or manual index tracking would be verbose, harder to maintain, and potentially slower due to additional template parsing overhead. Stick with preprocessing or custom filters for clarity and performance.

For further insights on optimizing templates in Laravel applications, you can explore resources at https://laravelcompany.com.

Our network