我正在尝试找出在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为:$ container不可用,这意味着我无法呈现我的自定义页面.
真的有两个问题,这是处理自定义错误页面的正确方法,还是应该将响应传递给控制器?如果是这样,最好的方法是什么?
如果这是正确的,我如何在我的监听器中提供模板引擎?
小智 8
你应该加入你的听众
/**
*
* @var ContainerInterface
*/
private $container;
function __construct($container) {
$this->container = $container;
}
Run Code Online (Sandbox Code Playgroud)
你如何注册你的听众?你应该像服务一样注册Listener
像那样
core.exceptlistener:
class: %core.exceptlistener.class%
arguments: [@service_container]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
Run Code Online (Sandbox Code Playgroud)
最好的方法是不要使用service_container.最好的方法是只注册必要的服务.
像那样
/**
*
* @var Twig_Environment
*/
private $twig;
function __construct($twig) {
$this->twig = $twig;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11627 次 |
| 最近记录: |