twig模板引擎,使用静态函数或变量

Ale*_*lex 15 php templates twig

有没有办法调用静态函数或在树枝中使用静态变量?

我有一类静态辅助函数,并希望在模板中使用一个或两个.

Ale*_*lex 23

几个方式我最终做到了.

首先是一个可以调用静态函数的函数.

$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;
}
Run Code Online (Sandbox Code Playgroud)

然后可以像,

{{ staticCall('myClass', 'mymethod', [optional params]) }}
Run Code Online (Sandbox Code Playgroud)

另一种是使用魔法.

将类添加到render $ context

$data['TwigRef']  = new TheClass();

class TheClass
{
    public function __call($name, $arguments) {
        return call_user_func_array(array('TheClass', $name), $arguments);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后可以像,

{{ TwigRef.myMethod(optional params) }}
Run Code Online (Sandbox Code Playgroud)

可能最好添加一些额外的检查,以便只调用已批准的函数调用.

  • 我以前见过这个.我还没有看到它的位置.请问,在SF2项目中,这段代码应该放在哪里?$ loader定义在哪里? (3认同)