Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig template engine, using a static function or variable

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.

like image 573
Alex Avatar asked Jul 27 '11 12:07

Alex


1 Answers

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.

like image 104
Alex Avatar answered Sep 25 '22 00:09

Alex