Is there a way to call a static function or use a static variable in twig?
I have a class of static helper functions and want to use one or two in a template.
Couple ways I've ended up doing it.
First is a function that can call a static function.
$twig = new Twig_Environment($loader);
$twig->addFunction('staticCall', new Twig_Function_Function('staticCall'));
function staticCall($class, $function, $args = array())
{
if (class_exists($class) && method_exists($class, $function))
return call_user_func_array(array($class, $function), $args);
return null;
}
Can then be used like,
{{ staticCall('myClass', 'mymethod', [optional params]) }}
The other is to use a magic method.
Add the class to the render $context
$data['TwigRef'] = new TheClass();
class TheClass
{
public function __call($name, $arguments) {
return call_user_func_array(array('TheClass', $name), $arguments);
}
...
}
Can then be used like,
{{ TwigRef.myMethod(optional params) }}
Probably best to add some extra checks so only approved functions call be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With