twigHow to use a PHP function in Twig?
Twig is a templating language for PHP, and it's possible to use PHP functions in Twig. To do this, you need to register the function as a Twig extension.
Example code
$twig = new Twig_Environment($loader);
$twig->addExtension(new Twig_Extension_StringLoader());
$twig->addFunction(new Twig_SimpleFunction('my_php_function', 'my_php_function'));
This code registers the my_php_function function as a Twig extension. Now you can use it in Twig templates like this:
{{ my_php_function('foo', 'bar') }}
Code explanation
$twig = new Twig_Environment($loader);- creates a new Twig environment.$twig->addExtension(new Twig_Extension_StringLoader());- adds the StringLoader extension to the Twig environment.$twig->addFunction(new Twig_SimpleFunction('my_php_function', 'my_php_function'));- registers themy_php_functionfunction as a Twig extension.{{ my_php_function('foo', 'bar') }}- calls themy_php_functionfunction in a Twig template.
Helpful links
More of Twig
- How to trim a string in PHP Twig?
- How to get a substring in PHP Twig?
- How to integrate Twig with Yii2?
- How to use Twig in PHP to get the current year?
- How to prevent Template Injection in PHP Twig?
- How to handle whitespace in Twig with PHP 7.4?
- How to create a template in PHP Twig?
- How to use the Twig library with PHP?
- How to require a PHP file in Twig?
See more codes...