doukunsan5553 2014-04-07 21:19
浏览 36
已采纳

Twig“无法添加功能”

I'm using twig, and i'm attempting to add a function.

        $Func = new \Twig_SimpleFunction('placeholder', function ($title) {
            $this->module->CurrentPage->addPlaceholder($title);
        });
        \App::make('twig')->addFunction($Func);

I will get the following exception

Unable to add function "placeholder" as extensions have already been initialized.

I've checked twice that the "addFunction" is executed before the twig "loadTemplate". So, it does not seem to be the problem.

Does anyone have a hint, or an idea about this? Or what its all about. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • drcigvoy48900 2014-08-25 06:33
    关注

    You need to add twig functions right after you created Twig_Environment instance. For example, the following WILL NOT work:

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

    Because Lexer is initialized before functions are added. You need to make it like this:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址