twig template engine, using a static function or variable(twig 模板引擎,使用静态函数或变量)
本文介绍了twig 模板引擎,使用静态函数或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 twig 中调用静态函数或使用静态变量?
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.
推荐答案
我最终做了几种方法.
首先是一个可以调用静态函数的函数.
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;
}
然后可以像这样使用,
{{ staticCall('myClass', 'mymethod', [optional params]) }}
另一种是使用魔法.
将类添加到渲染 $context
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);
}
...
}
然后可以像这样使用,
{{ TwigRef.myMethod(optional params) }}
最好添加一些额外的检查,以便只调用批准的函数.
Probably best to add some extra checks so only approved functions call be called.
这篇关于twig 模板引擎,使用静态函数或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:twig 模板引擎,使用静态函数或变量


猜你喜欢
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01