我有一个twig扩展,它有一个方法,它使用来自不同控制器的另一个方法通过依赖jsonResponse呈现json输出。
如何在枝条扩展中渲染控制器?
下面的代码似乎不起作用,因为render()需要一个视图文件而不是一个控制器。我现在正在引用一个控制器。
class AreaExtension extends \Twig_Extension {
public function add()
{
$outputJson = $this->container->get('templating')->render(new ControllerReference('CMSCoreBundle:Area:index'));
}
}
答案 0 :(得分:5)
$ref = new ControllerReference('CMSCoreBundle:Area:index');
$this->handler->render( $ref, 'inline', $options );
其中$this->handler
是fragment.handler
服务。
在你的情况下:
$outputJson = $this->container->get('fragment.handler')->render(new ControllerReference('CMSCoreBundle:Area:index'));
您可以在此symfony twig扩展中找到完整示例,请参阅: https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php#L28 和 https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php#L41