gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:52:44 25 4
gpt4 key购买 nike

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

我有一类静态辅助函数,想在模板中使用一两个。

最佳答案

我最终采用了几种方法。

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

$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;
}

然后可以这样使用,

{{ staticCall('myClass', 'mymethod', [optional params]) }}

另一种是使用魔法。

将类添加到渲染 $context

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

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

...
}

然后可以这样使用,

{{ TwigRef.myMethod(optional params) }}

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

关于php - twig 模板引擎,使用静态函数或变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6844266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com