2016-06-09 90 views

回答

1

感谢您使用微内核设置。以下是如何覆盖异常视图。

1.创建一个自定义ExceptionController

首先,我们要去创造我们自己的ExceptionController延伸基地ExceptionController。这将允许我们覆盖模板路径。

<?php 

    namespace AppBundle\Controller\Exception; 

    use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; 
    use Symfony\Component\HttpFoundation\Request; 

    class ExceptionController extends BaseExceptionController 
    { 
     /** 
      * @param Request $request 
      * @param string $format 
      * @param int $code 
      * @param bool $showException 
      * 
      * @return string 
      */ 
     protected function findTemplate(Request $request, $format, $code, $showException) 
     { 
      $name = $showException ? 'exception' : 'error'; 
      if ($showException && 'html' == $format) { 
       $name = 'exception_full'; 
      } 

      // For error pages, try to find a template for the specific HTTP status code and format 
      if (!$showException) { 
       $template = sprintf('AppBundle:Exception:%s%s.%s.twig', $name, $code, $format); 
       if ($this->templateExists($template)) { 
        return $template; 
       } 
      } 

      // try to find a template for the given format 
      $template = sprintf('@Twig/Exception/%s.%s.twig', $name, $format); 
      if ($this->templateExists($template)) { 
       return $template; 
      } 

      // default to a generic HTML exception 
      $request->setRequestFormat('html'); 

      return sprintf('@Twig/Exception/%s.html.twig', $showException ? 'exception_full' : $name); 
     } 
    } 

2.创建的错误模板

了不同的错误代码创建模板:

  • error.html.twig
  • error403.html.twig
  • error404 .html.twig

在这个例子中,除了模板将被放置在AppBundle/Resources/views/Exception/

3.改写默认ExceptionController

现在让我们来点我们在配置新的异常控制器。

twig: exception_controller: app.exception_controller:showAction

0

我很喜欢你的解决方案,但我发现另一种方式如何做到这一点没有自定义异常控制器。

我意识到,当您存储内核类时,会在目录的Resources目录中自动检查重写模板。

所以,在您的回购结构是:

/Resources/TwigBundle/views/Exception/ 

最后,我改变了一点点的目录结构与内部的内核文件中的“应用程序”目录。就像在默认的Symfony项目中一样。