Twoez
Twoez

Reputation: 548

How can I render a controller action within a twig extension?

I do have a twig extension which has a method that uses another method from a different controller to render a json output via dependency jsonResponse.

How can I render a controller within a twig extension?

The following code below doesn't seem to work, because render() needs a view file instead of a controller. And I am now referencing to a controller.

class AreaExtension extends \Twig_Extension {

    public function add()
    {

        $outputJson = $this->container->get('templating')->render(new ControllerReference('CMSCoreBundle:Area:index'));
    }
}

Upvotes: 3

Views: 1447

Answers (1)

$ref = new ControllerReference('CMSCoreBundle:Area:index');
$this->handler->render( $ref, 'inline', $options );

Where $this->handler is the fragment.handler service.

In your case:

$outputJson = $this->container->get('fragment.handler')->render(new ControllerReference('CMSCoreBundle:Area:index'));

You can find a full example in this symfony twig extension, see: https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php#L28 and https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php#L41

Upvotes: 5

Related Questions