Currently I place my function in a class and pass an instance of this class into template and call my required function as a class method.
{{ unneededclass.blah(
Although you cannot PHP callable directly, twig is extensible. You can add a callable filter, so you can apply to PHP functions passed to template.
namespace My\Twig\Extension;
class LambdaFilter extends \Twig_Extension {
public function getName() {
return 'lambda_filter';
}
public function getFilters() {
return array(
new \Twig_SimpleFilter('call', array($this, 'doCall'))
);
}
public function doCall() {
$arguments = func_get_args();
$callable = array_shift($arguments);
if(!is_callable($callable)) {
throw new InvalidArgumentException();
}
return call_user_func_array($callable, $arguments);
}
}
Now if you pass variable my_func
to template, you can do my_func|call(arg1, arg2)
. You can even do higher order functions "array_filter"|call(my_array, my_func)
and you can always do more things in filter like accepting array as parameters and so on.