Search code examples
phpsymfonyloopstwigcycle

"While" and "repeat" loops in Twig


Are there any nice ways to use while and repeat loops in Twig? It is such a simple task, but without macros I can't find anything nice and simple.

At least do an infinite cycle and then break it in a condition?

EDIT:

I mean something like

do {
    // loop code
} while (condition)

or

while (condition) {
    // loop code
}

Edit 2:

Looks like it is not supported natively by twig same reason as it is not supported neither continue; or break; statements.

https://github.com/twigphp/Twig/issues/654


Solution

  • In a nutshell: no. This functionality implies advanced logic, which should be in your business logic, not in the template layer. It's a prime example of the separation of concerns in MVC.

    Twig supports for-loops completely, which should suffice if you code correctly - being that complex conditional decisions on which data to display are taken in the business logic where they belong, which then pass a resulting array 'ready to render' to the templates. Twig then supports all nice features only needed for rendering.