The method Controller::redirect()
is in fact, creating a new RedirectResponse
object.
The default template is hard-coded into the response but here are some workarounds.
In this example, I will use a TWIG template, hence I need the @templating
service, but you can use whatever you want to render the page.
First, create your template 301.html.twig
into your Acme/FooBundle/Resources/views/Error/
with the content you want.
@AcmeFooBundle/Resources/views/Error/301.html.twig
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url={{ uri }}" />
</head>
<body>
You are about to be redirected to {{ uri }}
</body>
</html>
From an event listener
If you want this template to be global on any RedirectResponse
you can create an event listener which will listen to the response and check whether the response given is an instance of RedirectResponse
This means that you can still use return $this->redirect
in your controller, only the content of the response will be affected.
services.yml
services:
acme.redirect_listener:
class: AcmeFooBundleListenerRedirectListener
arguments: [ @templating ]
tags:
-
name: kernel.event_listener
event: kernel.response
method: onKernelResponse
AcmeFooBundleListenerRedirectListener
use SymfonyComponentTemplatingEngineInterface;
use SymfonyComponentHttpKernelEventFilterResponseEvent;
use SymfonyComponentHttpFoundationRedirectResponse;
class RedirectListener
{
protected $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
if (!($response instanceof RedirectResponse)) {
return;
}
$uri = $response->getTargetUrl();
$html = $this->templating->render(
'AcmeFooBundle:Error:301.html.twig',
array('uri' => $uri)
);
$response->setContent($html);
}
}
From a controller
Use this if you want to change the template directly from an action.
The modification will only be available for the given action, not global to your application.
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpKernelEventFilterResponseEvent;
class FooController extends Controller
{
public function fooAction()
{
$uri = $this->generateUrl($_redirectTo);
$response = new RedirectResponse($uri, 301);
$response->setContent($this->render(
'AcmeFooBundle:Error:301.html.twig',
array( 'uri' => $uri )
));
return $response;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…