Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call Static Function In Symfony2 Twig Template

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;
    }
}
like image 970
overshadow Avatar asked Oct 03 '15 07:10

overshadow


2 Answers

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') %}
like image 185
Bramus Avatar answered Oct 15 '22 19:10

Bramus


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() }}
like image 42
qwertz Avatar answered Oct 15 '22 20:10

qwertz