Updating Symfony 2.4 : “Rendering a fragment can only be done when handling a Request.”

丶灬走出姿态 提交于 2019-12-02 02:44:49

问题


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 ?


回答1:


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

 $this->getContainer()->get('request_stack')->push(Request::createFromGlobals());



回答2:


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


来源:https://stackoverflow.com/questions/21684218/updating-symfony-2-4-rendering-a-fragment-can-only-be-done-when-handling-a-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!