Creating a custom Twig filter
Similar to a Twig function used to extract or generate content, a Twig filter can be used to transform a value into something different.
We can use the same WeatherExtension
class that we used before to add our custom functions, but this time we’ll implement the getFilters()
method:
public function getFilters(): array { return [ new TwigFilter( 'celsius_to_fahrenheit', [$this, 'celsiusToFahrenheit'] ), ]; }
Staying in the field of meteorology, we’ve implemented a Twig filter to convert a temperature value from Celsius to Fahrenheit. The code for the filter is a simple one-line method:
public function celsiusToFahrenheit( float $celsius ): float { return $celsius * 1.8 + 32; }
WeatherExtension
is already tagged to be a Twig extension (in the...