树枝模板引擎,使用静态函数或变量 [英] twig template engine, using a static function or variable

查看:87
本文介绍了树枝模板引擎,使用静态函数或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在树枝中调用静态函数或使用静态变量?

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]) }}

另一种是使用魔术方法.

The other is to use a magic method.

将类添加到渲染$ 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.

这篇关于树枝模板引擎,使用静态函数或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆