How to call my static function in twig template without passing through controller?
For example:
...
{{ MyStaticClass::getData() }}
...
My Static Class:
class MyStaticClass {
const v1 = 'Value1';
const v2 = 'Value2';
...
public static function getData() {
...
return $data;
}
}
A generic approach is to register a Twig helper function named callstatic
to make the call.
$twig->addFunction(new \Twig_SimpleFunction('callstatic', function ($class, $method, ...$args) {
if (!class_exists($class)) {
throw new \Exception("Cannot call static method $method on Class $class: Invalid Class");
}
if (!method_exists($class, $method)) {
throw new \Exception("Cannot call static method $method on Class $class: Invalid method");
}
return forward_static_call_array([$class, $method], $args);
}));
The main advantage of this approach is that it will work with any class and method combination.
Usage:
{# This will call \Mynamespace\Mypackage\Myclass::getStuff(); #}
{% set result = callstatic('\\Mynamespace\\Mypackage\\Myclass', 'getStuff') %}
It also supports arguments:
{# This will call \Mynamespace\Mypackage\Myclass::getStuff('arg1', 'arg2'); #}
{% set result = callstatic('\\Mynamespace\\Mypackage\\Myclass', 'getStuff', 'arg1', 'arg2') %}
Instead of writing a Twig extension an easier / less bloated solution can sometimes be to simply pass a new instance of the class with the static methods to twig.
eg
// ...
$viewVars['MyStaticClass'] = new MyStaticClass();
// ...
$html = $twig->render('myTemplate.html.twig', $viewVars);
and in twig:
{{ MyStaticClass.getData() }}
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