简体   繁体   中英

Returning a Template from a Twig Extension

I have a form that is placed on many pages of my site, and I wanted to write a Twig Extension to build and handle the form. I thought that if I inject the Twig templating service and render a template with the form rendered, it would work. But I got a circular reference. My question is how to I return that template from the extension?

Let's say you have the action that has the form:

public function formAction()
{
    //Code goes here with no difference from a regular action
    return $this->render('MyBundle:Base:form.html.twig', array('form' => $form->createView()));
}

Let's say MyBundle:Base:form.html.twig is a Twig template with all the markup you will need to render the form. Let's say the controller is in MyBundle:Form:form , and a template every page (but the form template) has, MyBundle:Base:template.html.twig . In that template, add the following line wherever you wish:

{{ render(controller('MyBundle:Form:form')) }}

That way you can "inject" whatever method you want in all of your pages. You would then set the action of the form to any controller action so it can process it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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