How do I create a custom twig function?

Aero can extend Twig to add custom functions that can then be used throughout the shop. To create a custom twig function, we have to access a service provider that is of our concern - e.g. AppServiceProvider or a Service Provider belonging to a module.

In order to create a custom twig function, we have to add the following piece of code to a Service Provider of our choice:

TwigFunctions::add(new TwigFunction('new_function', function () {
        // Handle the function call

Anything within the above function will be processed after new_function() is ran in the frontend.

Twig functions can also be passed values directly from the frontend.


new TwigFunction('image_factory', static function ($width, $height, $path = '') {
        return new ImageFactory($width, $height, $path);

The above twig function requires the width and the height to call another function in the backend responsible for creating an Image Factory.

If instantiated correctly, the function should now be callable by its defined name.


Options and functions

There are a number of options and functions that are readily available by Twig Functions. The usage of these functions can be explained in the official documentation.

Articles in this section

Was this article helpful?
0 out of 0 found this helpful