Call PHP function from Twig template Call PHP function from Twig template symfony symfony

Call PHP function from Twig template


Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions,write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.


There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.


I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:
Twig2:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));

Twig 3:

$this->twig->addFilter(new \Twig\TwigFilter('getVariations','getVariations'));

Twig 3 but as function instead of a filter:

$this->twig->addFunction(new \Twig\TwigFunction('getVariantsFunc', 'getVariations'));