Using Twig’s ‘filter’ and ‘sort’ Filters

When, like many Shopware developers, you switch from Smarty (Shopware 5) to Twig (Shopware 6), or anyhow you are new to Twig, you should take your time to go through Twig’s excellent documentation https://twig.symfony.com/doc/3.x/ – it’s worth while!

Twig comes with some really nice features that help you to improve readability of your code. Like, did you know, that you can use Twig’s filters not just with variables, but also for functions? One example are the filter and sort functions available with the for function.

The following code snipped prints a price list for a product with quantity based prices on the product detail page:

filter works like adding an if clause to the loop. The above filtered for loop is equivalent to:

Note you may add as many filter filters to the for as you like. The benefit of using a filter is a) in potential performance optimisation and b) in keeping the code readable, avoiding nested or lengthy complex if statements.

But what I personally even like more is the sort filter. Can’t even think of what I would have had to do to get this working with Smarty …

A comprehensive list of available filters can be found here: https://twig.symfony.com/doc/3.x/filters/index.html

Also note that Shopware 6 extends Twig with many extra functions and filters, see here for a full list: https://developer.shopware.com/docs/resources/references/storefront-reference/twig-function-reference

Questions? Remarks?

Share your thoughts and insight with our fellow readers using the comment section below!

Leave a Reply