What you'll need to do is not too difficult. Symfony allows you to explicitly specify which controller handles your exceptions. So, in your config.yml, you can specify the exception controller under your twig configuration:
since Symfony 2.2
twig:
exception_controller: my.twig.controller.exception:showAction
services:
my.twig.controller.exception:
class: AcmeDemoBundleControllerExceptionController
arguments: [@twig, %kernel.debug%]
up to Symfony 2.1:
twig:
exception_controller: AcmeDemoBundleControllerExceptionController::showAction
Then you can create a custom showAction that displays a custom error page based on a route:
<?php
namespace AcmeDemoBundleController;
use SymfonyComponentHttpKernelExceptionFlattenException;
use SymfonyComponentHttpKernelLogDebugLoggerInterface;
use SymfonyComponentHttpFoundationResponse;
use SymfonyBundleTwigBundleControllerExceptionController as BaseExceptionController;
class ExceptionController extends BaseExceptionController
{
public function showAction(FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
{
if ($this->container->get('request')->get('_route') == "abcRoute") {
$appTemplate = "backend";
} else {
$appTemplate = "frontend";
}
$template = $this->container->get('kernel')->isDebug() ? 'exception' : 'error';
$code = $exception->getStatusCode();
return $this->container->get('templating')->renderResponse(
'AcmeDemoBundle:Exception:' . $appTemplate . '_' . $template . '.html.twig',
array(
'status_code' => $code,
'status_text' => Response::$statusTexts[$code],
'exception' => $exception,
'logger' => null,
'currentContent' => '',
)
);
}
}
Obviously you should probably customize the if statement where it tests the current route to fit your needs, but this should do it.
You might want to add code that defaults to the normal Twig error pages if you don't have a specific error template created. For more information, check out the code in
SymfonyBundleTwigBundleControllerExceptionController
as well as
SymfonyComponentHttpKernelEventListenerExceptionListener
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…