Updating Symfony 2.4 : “Rendering a fragment can o

2019-02-28 22:12发布

Since I migrated to Symfony 2.4, I'm getting the following error message :

Rendering a fragment can only be done when handling a Request.

It's happening because, on some pages, I'm rendering some templates with Twig inside some pages which are handled by another older framework, by doing $sf2->container->get('twig')->render("MyBundle::my-template.html.twig");.

So yes, that's right that Symfony 2 isn't handling those requests, but I still want to render those templates with Twig ! Why can't I do that (anymore) ?! And how to fix that ?

Here is the code I'm executing to "boot" SF2 in my older project :

$loader = require_once __DIR__.'/../../../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../../../app/AppKernel.php';

$kernel = new AppKernel('bootstrap', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$kernel->boot();
$kernel->getContainer()->enterScope('request');
$kernel->getContainer()->set('request', $request, 'request');
$this->container = $kernel->getContainer();

EDIT : By the way, it might be related to that : Symfony 2.4 Rendering a controller in TWIG throws "Rendering a fragment can only be done when handling a Request." Exception . Though, I don't want to downgrade to Symfony 2.3, and deleting the vendor directory didn't fix my problem.

EDIT² : I found out that the problem is because of the new RequestStack.

In HttpKernel, handleRaw(Request $request, $type = self::MASTER_REQUEST) normally push the request to the RequestStack ($this->requestStack->push($request);). So if I add a public method pushRequestStack($request) to the HttpKernel it works.. But how could I do it properly ? I don't find any public method able to get the $requestStack from HttpKernel (so I can push the request externally)..

And I can't use the "normal" method ($kernel->handle($request)) because it would throw some exceptions, for example for the route that doesn't exist, or also for the session that has already been started by PHP..

In conclusion, is there any way to "push" my/any request to the requestStack without completly handling the request ?

2条回答
Deceive 欺骗
2楼-- · 2019-02-28 22:34

You have to push a new Request in the "request_stack" from your Sf2 command.

 $this->getContainer()->get('request_stack')->push(Request::createFromGlobals());
查看更多
等我变得足够好
3楼-- · 2019-02-28 22:50

I had the same problem and solved this by rebuilding the bootstrap with this command:

php vendor/bundles/Sensio/Bundle/DistributionBundle/Resources/bin/build_bootstrap.php app
查看更多
登录 后发表回答