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_function
function as a Twig extension.{{ my_php_function('foo', 'bar') }}
- calls themy_php_function
function in a Twig template.
Helpful links
More of Twig
- How to use a Twig file in PHP?
- Where can I convert PHP to Twig online?
- How to check if a string contains a substring in PHP Twig?
- How to use Twig in PHP to get the current year?
- How to use Slim/Twig-View in PHP?
- How to use PHP variables in Twig?
- How to use the Twig library with PHP?
- How to use yield in Twig with PHP?
- How to use a switch case in PHP Twig?
See more codes...