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 模板引擎,使用静态函数或变量


基础教程推荐
猜你喜欢
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- php中的PDF导出 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01