Bruno
Bruno

Reputation: 1128

symfony - call a controller-action within a twig extention

I'm trying to call a controller from a twig extention. I do not want to call the controller as a service since I'd lose all the fancy shortcuts.

Want I want to achieve is to call the controller like twig do it when you do :

 {{ render(controller(
   'AppBundle:Article:recentArticles',
   { 'max': 3 }
 )) }}

I looked at the sourcecode of the "render" and tried to find the "controller" twig's functions, but I did not managed to understand how to do. From now I achieved an unsatisfying but functionnal code :

In my twig extention :

return $environment->render('FooBundle:TwigExtension/CmsExtension:cmsRenderHook.html.twig', [
    'hook'  => $hook,
]);

In the CmsExtension:cmsRenderHook.html.twig template :

{{ render(controller(hook.stringControllerAction, hook.arrayParameters)) }}

I think (maybe wrongly) that it would be faster to call it without the template step.

EDIT : I finally successed to code this :

$environment->getExtension('Symfony\Bridge\Twig\Extension\HttpKernelExtension')->renderFragment(
    $environment->getExtension('Symfony\Bridge\Twig\Extension\HttpKernelExtension')->controller(
        $hook['action'],
        $hook['jsonParameters']
    )
);

(I did a grep in twig's cache and reproduced it compiled version). my only concern is about referring to Symfony\Bridge\Twig\Extension\HttpKernelExtension, i'd rather let twig handle this choice, but I can't find out how.

I have two questions: - do you think that Symfony\Bridge\Twig\Extension\HttpKernelExtension is stable enought to refere explicitly to it? - if not how would you do to let twig handle it?

Upvotes: 1

Views: 770

Answers (1)

OrangeSalty
OrangeSalty

Reputation: 202

You could also get the Twig_SimpleFunction from the Twig_Environment:

$renderFunction = $environment->getFunction('render'); // get the env via initRuntime(..) in your extension
$callable = $renderFunction->getCallable();

However, I would not recommend relying on Twig internals. You should probably extract the functionality into a service.

Upvotes: 1

Related Questions