Loop list in batches using Twig (or plain PHP)

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 Bootstrap, 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?

I realized PHP has a built-in function that handles this. It’s called array_chunk which, of course, splits an array into chunks (or batches as I recalled, and the reason why I hadn’t been able to find it on the docs.)

Edit 19 Jul: Added plain PHP version.

Use only grid system (or other component) from Bootstrap

PSA: You don’t need to add the whole Bootstrap code and a zillion dependencies and plugins just because it’s easier to use col-md-3 than hacking some CSS to float a few divs.

Use the link below to download a customized version of Bootstrap. Need the Grid System? Perhaps the pretty Glyphycons or tooltips? This has you covered:

Customize & Download Bootstrap