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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题