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. AppServiceProvideror a Service Providerbelonging to a module.
In order to create a custom twig function, we have to add the following piece of code to a Service Providerof 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.
Example:
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