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

查看:21
本文介绍了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 模板引擎,使用静态函数或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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