symfony - Call PHP function from Twig template

Solution:

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.

Answer

Solution:

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.

Answer

Solution:

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'));

Answer

Solution:

You can check your all defined function by

$arr = get_defined_functions();
print_r($arr);

this will give you array of all functions in if your function exist in it you can use it like:

 {{ user.myfunction({{parameter}}) }}

Answer

Solution:

I know this is an old thread. But with symfony 3.3 I did this:

{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}

Answer

Solution:

While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment

$twig->registerUndefinedFunctionCallback(function ($name) {
        // security
        $allowed = false;
        switch ($name) {
            // example of calling a wordpress function
            case 'get_admin_page_title':
                $allowed = true;
                break;
        }

        if ($allowed && function_exists($name)) {
            return new Twig_Function_Function($name);
        }

        return false;
    });

This is from the Twig recipe page

Haven't tried calling a function on an object as the original question requested

Answer

Solution:

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

Answer

Solution:

If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:

function evilEvalPhp($eval, $args = null)
{
    $result = null;
    eval($eval);
    return $result;
}

Source