调用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中将细枝扩展注册为服务: