私はSymfony2内のカスタムエラーページを処理する最良の方法を見つけようとしています。これには500や404などが含まれます。
独自のカスタムテンプレート(error404.html.twigなど)を作成して、これらを適切にレンダリングできます。問題は、ページの一貫性を維持するために、アプリでいくつかの変数をベーステンプレートに渡す必要があることです。組み込みの例外ハンドラーを使用すると、必要な変数が使用できなくなります。
カスタム例外イベントリスナーを正常にセットアップし、サービスとして登録しました。
namespace MyCo\MyBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class MyErrorExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// We get the exception object from the received event
$exception = $event->getException();
if($exception->getStatusCode() == 404)
{
//$engine = $this->container->get('templating');
//$content = $engine->render('MyBundle:Default:error404.html.twig');
//return $response = new Response($content);
/* Also Tried */
//$templating = $this->container->get('templating');
//return $this->render('MyBundle:Default:index.html.twig');
$response = new Response($templating->render('MyBundle:Exception:error404.html.twig', array(
'exception' => $exception
)));
$event->setResponse($response);
}
}
}
:$ containerが利用できないため、これは機能しません。つまり、カスタムページをレンダリングできません。
したがって、2つの質問があります。これは、カスタムエラーページを処理する正しい方法ですか、それとも応答をコントローラーに渡す必要がありますか?もしそうなら、それを行うための最良の方法は何ですか?
これが正しければ、リスナー内でテンプレートエンジンを利用できるようにするにはどうすればよいですか?