php twig 模板引擎,使用静态函数或变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6844266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
twig template engine, using a static function or variable
提问by Alex
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.
我有一类静态辅助函数,想在模板中使用一两个。
回答by Alex
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
将类添加到渲染 $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.
可能最好添加一些额外的检查,以便只调用批准的函数调用。
回答by hakre
You can dynamically add functions to your twig templates by registering them. Either they are already callable or you alias your static function by a name of it's own:
您可以通过注册将函数动态添加到树枝模板中。要么它们已经是可调用的,要么你用它自己的名字为你的静态函数取别名:
$twig = new Twig_Environment($loader);
$twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
See the Functionssection in Extending Twig.