aaronadal/twig-list-loop-bundle
Install the Bundle Add via Composer:
composer require aaronadal/twig-list-loop-bundle
Enable in config/bundles.php:
return [
// ...
Aaronadal\TwigListLoopBundle\AaronadalTwigListLoopBundle::class => ['all' => true],
];
Basic Usage in Twig
The bundle extends Twig with a loop filter for lists. Example:
{% set items = ['apple', 'banana', 'cherry'] %}
<ul>
{% for item in items|loop %}
<li>{{ item }}
- First: {{ loop.first }}, Last: {{ loop.last }}, Index: {{ loop.index }}
</li>
{% endfor %}
</ul>
First Use Case
Replace manual loop counters with built-in loop variables for cleaner templates:
{% for user in users %}
<tr>
<td>{{ user.name }}</td>
<td>{{ loop.index }}</td> {# Auto-incremented #}
<td>{{ loop.reversedIndex }}</td> {# Countdown #}
</tr>
{% endfor %}
Dynamic Loop Variables
Use loop to avoid hardcoding counters:
{% for product in products %}
<div class="product {{ loop.first ? 'first' : '' }}">
{{ product.name }} ({{ loop.index }} of {{ loop.length }})
</div>
{% endfor %}
Conditional Styling Apply styles based on loop position:
{% for item in items %}
<li class="item-{{ loop.index }} {{ loop.even ? 'even' : 'odd' }}">
{{ item }}
</li>
{% endfor %}
Pagination-Friendly Loops Combine with Symfony’s pagination:
{% for page in paginator %}
<a href="{{ path('page', {'page': loop.index}) }}">
Page {{ loop.index }}
</a>
{% endfor %}
LoopExtension to add custom variables (e.g., loop.isFirstQuarter).config/app.php under extra.bundles.loop variables in PHPUnit:
$twig->addExtension(new \Aaronadal\TwigListLoop\Extension\LoopExtension());
Namespace Conflicts
Ensure no other Twig extensions override loop variables. Check for duplicate LoopExtension registrations.
Deprecated Methods The package is unmaintained (last release: 2019). Test thoroughly—some methods may behave unexpectedly in newer Twig/Symfony versions.
Zero-Length Lists
loop.length returns 0 for empty lists. Handle edge cases:
{% if loop.length > 0 %}
Total items: {{ loop.length }}
{% endif %}
dump to inspect loop variables:
{{ dump(loop) }}
Custom Loop Logic
Override the LoopExtension class to add logic (e.g., chunking):
// src/Twig/Extension/CustomLoopExtension.php
class CustomLoopExtension extends \Twig_Extension {
public function getFunctions() {
return [
new \Twig_SimpleFunction('custom_loop', [$this, 'customLoopLogic']),
];
}
}
Laravel Service Provider
Bind the extension manually in AppServiceProvider:
public function register() {
$this->app->singleton(\Twig_Extension_Interface::class, function () {
return new \Aaronadal\TwigListLoop\Extension\LoopExtension();
});
}
How can I help you explore Laravel packages today?