Twig"无法添加功能"

时间:2014-04-07 21:19:03

标签: php laravel 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"之前执行。所以,它似乎不是问题。

有没有人有这个暗示或想法?或者它的全部意义。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

您需要在创建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);