我正在使用 twig,我正在尝试添加一个功能。
$Func = new \Twig_SimpleFunction('placeholder', function ($title) {
$this->module->CurrentPage->addPlaceholder($title);
});
\App::make('twig')->addFunction($Func);
我会得到以下异常
Unable to add function "placeholder" as extensions have already been initialized.
我检查了两次“addFunction”在 twig“loadTemplate”之前执行。所以,这似乎不是问题所在。
有没有人对此有任何提示或想法?或者它是关于什么的。 提前致谢。
最佳答案
您需要在创建 Twig_Environment 实例后立即添加 twig 函数。例如,以下将不起作用:
$loader = new Twig_Loader_Filesystem($this->resourceRoot . '/views');
$twig = new Twig_Environment($loader, array(
'cache' => storage_path('twig'),
'debug' => Config::get('app.debug'),
'strict_variables' => true,
));
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{#', '#}'),
'tag_block' => array('{%', '%}'),
'tag_variable' => array('{^', '^}'),
'interpolation' => array('#{', '}'),
));
$twig->setLexer($lexer);
$function = new Twig_SimpleFunction('widget', function ($widget, array $params) {
WidgetFactory::renderWidget($widget, $params);
});
$twig->addFunction($function);
因为 Lexer 在添加函数之前被初始化。你需要这样做:
$loader = new Twig_Loader_Filesystem($this->resourceRoot . '/views');
$twig = new Twig_Environment($loader, array(
'cache' => storage_path('twig'),
'debug' => Config::get('app.debug'),
'strict_variables' => true,
));
$function = new Twig_SimpleFunction('widget', function ($widget, array $params) {
WidgetFactory::renderWidget($widget, $params);
});
$twig->addFunction($function);
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{#', '#}'),
'tag_block' => array('{%', '%}'),
'tag_variable' => array('{^', '^}'),
'interpolation' => array('#{', '}'),
));
$twig->setLexer($lexer);
关于php - Twig "Unable to add function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923309/