Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用Twig中的静态函数_Twig - Fatal编程技术网

调用Twig中的静态函数

调用Twig中的静态函数,twig,Twig,我是个新手。我有一个名为Session的类和一个名为get的静态函数,我想返回Session::get('user\u name')的内容。甚至可以不修改任何东西吗 我尝试了{constant('Namespace\\Session::get(“user_name”))}和{{Session.get('user_name')}},但似乎不起作用。我找到了答案。我只是在新的Twig\u环境($Twig\u loader) 细枝 {{ _call('Session', 'get', 'user_na

我是个新手。我有一个名为
Session
的类和一个名为
get
的静态函数,我想返回
Session::get('user\u name')
的内容。甚至可以不修改任何东西吗


我尝试了
{constant('Namespace\\Session::get(“user_name”))}
{{Session.get('user_name')}}
,但似乎不起作用。

我找到了答案。我只是在新的Twig\u环境($Twig\u loader)

细枝

{{ _call('Session', 'get', 'user_name')|raw }}

我找到了答案。我只是在新的Twig\u环境($Twig\u loader)

细枝

{{ _call('Session', 'get', 'user_name')|raw }}

您可以使用细枝扩展,如下所示:

class CustomExtension extends \Twig_Extension {


    public function getFunctions() {
        return array(
            new \Twig_SimpleFunction('static_call', array($this, '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;
    }

}
细枝中的用法:

{{ static_call('AppBundle\\Entity\\YourEntity', 'GetSomething', ['var1', 'var2']) }}

您可以使用细枝扩展,如下所示:

class CustomExtension extends \Twig_Extension {


    public function getFunctions() {
        return array(
            new \Twig_SimpleFunction('static_call', array($this, '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;
    }

}
细枝中的用法:

{{ static_call('AppBundle\\Entity\\YourEntity', 'GetSomething', ['var1', 'var2']) }}

在Symfony中将细枝扩展注册为服务:在Symfony中将细枝扩展注册为服务: