树枝“无法添加功能”


Twig "Unable to add function"

我正在使用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"是在树枝"loadTemplate"之前执行的。因此,这似乎不是问题所在。

有没有人对此有提示或想法?或者它的全部内容。提前谢谢。

您需要

在创建实例后立即添加 twig 函数Twig_Environment。例如,以下将不起作用:

$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);

因为词法分析器是在添加函数之前初始化的。你需要让它像这样:

$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);