Stefano php, milano

How to use any PHP function in Twig

A common reason I hear for using Blade instead of Twig with Laravel is the need to register with Twig each PHP function you need before you can use it in your templates.

This is by design, but there's a way around, if you need it:

$twig->addFunction(new Twig_SimpleFunction('php_*', function() {
    $arguments = func_get_args();
    $function = array_shift($arguments);
    return call_user_func_array($function, $arguments);
    }
));

Now you can use whatever function you want in your templates, for example the much needed str_rot13:


rot13 with makes me {{ php_str_rot13("happy")}} !

Just in case you use Laravel and the excellent TwigBridge by Rcrowe I suggest you to register this catch all function inside start/global.php in this way:

Event::listen('twigbridge.twig', function(Twig_Environment $twig) {
    $twig->addFunction(new Twig_SimpleFunction('php_*', function() {
        $arguments = func_get_args();
        $function = array_shift($arguments);
        return call_user_func_array($function, $arguments);
    }
    ));
});

From now on you'll be able to use any PHP function you like by just prepending php_ to the name of the function.

Tags: twig, laravel