// $twig is a Twig_Environment instance.
$twig->registerUndefinedFunctionCallback(function($name) {
if (function_exists($name)) {
return new Twig_SimpleFunction($name, function() use($name) {
return call_user_func_array($name, func_get_args());
});
}
throw new \RuntimeException(sprintf('Function %s not found', $name));
});
In a twig template:
{{ explode(",", "It's raining, cats and dogs.").0 | raw }}
this will output "It's raining". By default, returned values are escaped in Twig.
Twig_SimpleFunction is the preferred class to use. All other function related classes in Twig are deprecated since 1.12 (to be removed in 2.0).
In a Symfony2 controller:
$twig = $this->get('twig');