简体   繁体   English

Symfony 2 Twig表单功能不可用

[英]Symfony 2 Twig form functions not available

I am creating a new Twig Environment object inside a custom class, that class is being rendered from an existing twig file. 我在自定义类中创建一个新的Twig Environment对象,该类是从现有的twig文件呈现的。 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. 我试图在我的twig文件中渲染一个表单,该文件是从我的自定义类渲染的,但是在这个新的Twig_Environment对象表单函数不可用时,我尝试将现有的表单扩展从symfony自己的twig对象添加到我的新twig对象,那也不起作用。

$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" “电子邮件”form_start“在第8行的EmailUs.html.twig中不存在”

I was using symfony's own twig object to render the response but that was giving me the same error. 我正在使用symfony自己的twig对象来呈现响应,但这给了我同样的错误。 Can you help pls? 你能帮忙吗? I am using Symfony 2.3.4 我正在使用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. 如果我渲染一个普通的控制器,表单函数是可用的,如果我创建一个自定义的枝条对象,它们不能正常工作。

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;

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). 我主要将addExtension调用移到loadTemplate之前(否则扩展名已被初始化)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM