php - Twig "Unable to add function"

标签 php laravel twig

我正在使用 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/

相关文章:

php - 在线游戏的最佳数据库设置

symfony - 如何在Symfony 2.2中使用 “render”在Twig中插入 Controller ?

javascript - symfony2 + Assets : how to restrict a css to a print when using {% javascripts %}

wordpress - 木材分页

php - simplexml_load_string 有错误?

javascript - 视频上传验证不起作用

php - 在查询生成器上转换日期查询

mysql - 在 Laravel 迁移中,使用长度大于 255 的字符串

laravel - 如何将 Nexts.js 添加到 Laravel

php - 我需要使用 php 垂直显示一行