Symfony 2 Twig form functions not available

2019-05-22 23:10发布

问题:

I am creating a new Twig Environment object inside a custom class, that class is being rendered from an existing twig file. I am trying to render a form in my twig file which is being rendered from my custom class, however in this new Twig_Environment object form functions are not available, i have tried adding existing form extension from symfony's own twig object to my new twig object, that is not working either.

$path = 'some/directory'; // just simplifying here

$loader = new \Twig_Loader_Filesystem( $path );
$twig = new \Twig_Environment($loader, array(
     'cache' => __DIR__.'/../../../../../../app/cache/',
));
$tmpl = $twig->loadTemplate('EmailUs.html.twig');
$twig->addExtension( new \Symfony\Bridge\Twig\Extension\FormExtension( $this->pageObj->getContainer()->get('twig.form.renderer') ) );
$response = new Response();
$response->setContent($tmpl);
return $response;

The error i get is

"The function "form_start" does not exist in EmailUs.html.twig at line 8"

I was using symfony's own twig object to render the response but that was giving me the same error. Can you help pls? I am using Symfony 2.3.4

Form functions are available if i render a normal controller, they dont work fine if i create a custom twig object.

回答1:

I have solved it this way:

$loader = $pageFunctions->getContainer()->get('twig.loader');
$loader->addPath( $path );
$twig = new \Twig_Environment($loader, array(
    'cache' => __DIR__.'/../../../../../../app/cache/myTwig',
));  

foreach( $this->twig->getExtensions() as $ext ) {
    $twig->addExtension( $ext );
}

$tmpl = $twig->loadTemplate('EmailUs.html.twig');        

$rendered = $tmpl->display( array('control' => $this,
       'functions' => $pageFunctions,
       'params' => $params,
       'email_form'=>$form->createView() ) );

return $rendered;


回答2:

Here's my working code (executed inside a controller action):

$path = __DIR__.'/../Resources/views/'; /* twig loader path */
$loader = new \Twig_Loader_Filesystem($path);
$twig = new \Twig_Environment($loader);
$twig->addExtension( new \Symfony\Bridge\Twig\Extension\FormExtension($this->get('twig.form.renderer')));
$tmpl = $twig->loadTemplate('test.html.twig');
return new Response($tmpl->render(array()));

I've mainly moved the addExtension call before the loadTemplate one (otherwise extensions would have been already initialized).



标签: php symfony twig