Loop list in batches using Twig

Recently I had to loop through a series of elements in a WordPress template (thanks Timber), which happened to be using Bootstrap.

If you ever used BS, you are familiar with the following markup:

The problem here is very common. You have to:

  • Loop every 3/4/n items.
  • Insert a separator or whatever every 3/4/n items.

You can achieve this with modulo (divisibleby) and checking if the loop index is last and other weird magic. However, Twig introduced the batch filter in version 1.12.3, where you can make this much less cumbersome.

So, adapting the current example and their docs, this is how we achieve a clean loop:

Much better, right?