Существует несколько способов темизации страниц ошибок.
Способ 1 - переопределение шаблонов
Самый простой способ - создать в папке /app/Resources/TwigBundle/views/Exception/ файлы с именем error404.html.twig, error403.html.twig, error.html.twig и т.п. Теперь наши шаблоны будут срабатывать при вызове в контроллере:
throw $this->createNotFoundException('Page not found');
Подробнее тут.
Способ 2 - отдельный контроллер MyException
Если требуется передавать переменные в шаблоны ошибок - то первый способ не подойдёт. Придётся писать собственный Exception в отдельном контроллере.
Для этого в /app/config/config.yml необходимо прописать:
twig:
exception_controller: twig.controller.exception:showAction
Также прописываем теперь в /app/config/services.yml:
services:
twig.controller.exception:
class: ControlBundle\Controller\MyExceptionController
arguments: [@twig, %kernel.debug%, @doctrine.orm.default_entity_manager]
После этого необходимо создать контроллер MyExceptionController в нашем бандле ControlBundle и прописать в нём:
namespace ControlBundle\Controller;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MyExceptionController extends ExceptionController
{
public function __construct(\Twig_Environment $twig, $debug, EntityManager $em )
{
$this->twig = $twig;
$this->debug = $debug;
$this->em = $em;
}
/**
* Converts an Exception to a Response.
*
* A "showException" request parameter can be used to force display of an error page (when set to false) or
* the exception page (when true). If it is not present, the "debug" value passed into the constructor will
* be used.
*
* @param Request $request The request
* @param FlattenException $exception A FlattenException instance
* @param DebugLoggerInterface $logger A DebugLoggerInterface instance
*
* @return Response
*
* @throws \InvalidArgumentException When the exception template does not exist
*/
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
$currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
$showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
$code = $exception->getStatusCode();
return new Response($this->twig->render(
$this->findTemplate($request, $request->getRequestFormat(), $code, $showException),
array(
'status_code' => $code,
'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
'exception' => $exception,
'logger' => $logger,
'currentContent' => $currentContent,
'title' => 'Error 404',
'keywords' => '',
'description' => '',
'categories' => $this->em->getRepository('ControlBundle:Categories')->findBy(array('isActive' => '1')),
'counters' => $this->em->getRepository('ControlBundle:Counters')->findAll(),
)
));
}
}
Теперь также будут использоваться шаблоны из папки /app/Resources/TwigBundle/views/Exception/, но теперь мы можем передавать в них любые переменные.
Способ 3 - слушатель
Есть еще один способ переопределения страниц ошибок с помощью слушателя. Подробнее об этом способе рассказано тут.