在树枝视图中访问树枝扩展功能
问题描述:
我尝试访问我写的树枝扩展功能。在树枝视图中访问树枝扩展功能
// AppBundle/Twig/AppExtention.php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
public function getFunctions() {
return [
new \Twig_Function('testMethod', 'testMethod'),
];
}
public function testMethod() {
return 'blubb';
}
}
现在我尝试{{ testMethod() }}
访问funtion,但我得到了以下错误:
UndefinedFunctionException in <Hex for cached view>.php line 68: Attempted to call function "testMethod" from the global namespace.
我清除缓存,并试图寻找的错误,但我没有发现任何帮助过我。也许这里有人可以帮忙。
答
您正在定义您的Twig_Function
错误,因为它现在,您告诉Twig
寻找在任何类别以外定义的global function
。
如果你想告诉Twig
看当前的类中,你可以这样做:
public function getFunctions() {
return [
new \Twig_SimpleFunction('testMethod', array($this, 'testMethod')),
];
}
OK啊,是的,在我的情况下,我必须使用''Twig_SimpleFunction''。谢谢! – mgluesenkamp