2014-03-28 4 views
1

Я использую версию symfony 2.0 с шаблоном php. Как создать настраиваемую страницу ошибок с использованием шаблона php? У меня есть базовые знания в Symfony, любезно помочь мнеПользовательская страница ошибки в symfony 2.0 с использованием .html.php template

+3

вы можете прочитать [здесь] (http://symfony.com/doc/2.0/cookbook/controller/error_pages.html) – xiidea

ответ

1

по ссылке выше:

Чтобы переопределить шаблон по ошибке по умолчанию, который показывается конечному пользователю, создать новый шаблон, расположенный на приложения/Ресурсы/TwigBundle/просмотров /Exception/error.html.twig:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>An Error Occurred: {{ status_text }}</title> 
</head> 
<body> 
    <h1>Oops! An Error Occurred</h1> 
    <h2>The server returned a "{{ status_code }} {{ status_text }}".</h2> 
</body> 
</html> 

Вы также можете настроить определенные шаблоны ошибок в соответствии с кодом состояния HTTP. Например, создайте шаблон app/Resources/TwigBundle/views/Exception/error404.html.twig, чтобы отобразить специальную страницу для 404 (не найденных страниц).

EDIT: Я думаю, если вы хотите его в качестве шаблона PHP, и у вас есть правильные настройки в конфигурации

# app/config/config.yml 
framework: 
    # ... 
    templating: 
     engines: ['twig', 'php'] 

Вы должны быть в состоянии просто изменить расширение на .html.php и он должен работать. (И замена содержимого прут для содержания PHP Offcourse)

EDIT: Попробуйте ниже как app/Resources/TwigBundle/views/Exception/error.html.php

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>An Error Occurred: <?php echo $status_text ?></title> 
</head> 
<body> 
    <h1>Oops! An Error Occurred</h1> 
    <h2>The server returned a "<?php echo $status_code ?> <?php echo $status_text ?>".</h2> 
</body> 
</html> 

Пожалуйста, попробуйте и отчет. Thx

+0

Спасибо. Да, я использовал его и его работу в шаблоне ветви. Мне нужен этот .html.php шаблон. – kovarthan

+0

я отредактировал ответ выше –

+0

Я изменил вышеуказанное содержание и имя файла. Но снова я получаю страницу ошибки 404 по умолчанию. Есть ли какая-либо страница контроллера исключений или файл класса, доступный для изменения? Спасибо – kovarthan

2

Проблема: Symfony создала веточки ExceptionController. Это дизайн: вы можете увидеть здесь, что они выбрали только поддержку прутик для этого компонента, так что не беспокойтесь открытием билета с ними: https://github.com/symfony/symfony/issues/7285

Решением: Вы должны создать свой собственный ExceptionController. Оригинал находится в Symfony \ Bundle \ TwigBundle \ Controller \ ExceptionController. Я решил не продлевать оригинал, поскольку я недостаточно использовал его, чтобы гарантировать соединение.

Ниже приведен контроллер, в котором я оказался. Он сначала поддерживает поиск шаблонов ошибок PHP, и, не найдя его, он не сможет использовать встроенные ветви.

namespace Rate\CommonBundle\Controller; 

use Rate\CommonBundle\Entity\AjaxResponse; 
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; 
use Symfony\Component\HttpKernel\Exception\FlattenException; 
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 

/** 
* NOTE: when overriding twig exception/error templates in the app space, you MUST CLEAR CACHE AFTER ADDING A NEW ONE 
* 
* This file is specified to be used in parameters.yml 
* 
* For "non debug" environments (production), error templates will be used. For dev environments, exception 
* templates are used 
*/ 
class ExceptionController 
{ 
    /** 
    * @var \Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine 
    */ 
    protected $templating; 
    /** 
    * @var \Twig_Environment 
    */ 
    protected $twig; 
    /** 
    * @var bool 
    */ 
    protected $debug; 

    public function __construct($templating, \Twig_Environment $twig, $debug) 
    { 
     $this->templating = $templating; 
     $this->twig = $twig; 
     $this->debug = $debug; 
    } 

    /** 
    * Converts an Exception to a Response. 
    * 
    * @param Request    $request The request 
    * @param FlattenException  $exception A FlattenException instance 
    * @param DebugLoggerInterface $logger A DebugLoggerInterface instance 
    * @param string    $_format The format to use for rendering (html, xml, ...) 
    * 
    * @return Response 
    * 
    * @throws \InvalidArgumentException When the exception template does not exist 
    */ 
    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $_format = 'html') 
    { 
     $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1)); 
     $code = $exception->getStatusCode(); 
     $template = $this->findTemplate($request, $_format, $code, $this->debug); 

     if ($template->get('engine') == 'php') { 
      $engine =& $this->templating; 
     } else { 
      $engine =& $this->twig; 
     } 

     return new Response($engine->render(
      $template, 
      array(
       'status_code' => $code, 
       'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '', 
       'exception'  => $exception, 
       'logger'   => $logger, 
       'currentContent' => $currentContent, 
      ) 
     )); 
    } 

    /** 
    * @param int  $startObLevel 
    * 
    * @return string 
    */ 
    protected function getAndCleanOutputBuffering($startObLevel) 
    { 
     if (ob_get_level() <= $startObLevel) { 
      return ''; 
     } 

     Response::closeOutputBuffers($startObLevel + 1, true); 

     return ob_get_clean(); 
    } 

    /** 
    * @param Request $request 
    * @param string $format 
    * @param int  $code  An HTTP response status code 
    * @param bool $debug 
    * 
    * @return TemplateReference 
    */ 
    protected function findTemplate(Request $request, $format, $code, $debug) 
    { 
     $name = $debug ? 'exception' : 'error'; 
     if ($debug && 'html' == $format) { 
      $name = 'exception_full'; 
     } 

     // when not in debug, try to find a template for the specific HTTP status code and format 
     //if (!$debug) { 
      $template = new TemplateReference('RateCommonBundle', 'Exception', $name.$code, $format, 'php'); 
      if ($this->templating->exists($template)) { 
       return $template; 
      } 
     //} 

     // try to find a template for the given format 
     $template = new TemplateReference('RateCommonBundle', 'Exception', $name, $format, 'php'); 
     if ($this->templating->exists($template)) { 
      return $template; 
     } 

     // default to a generic HTML exception 
     $request->setRequestFormat('html'); 
     // Check if we have a custom one 
     $template = new TemplateReference('RateCommonBundle', 'Exception', $name, 'html', 'php'); 
     if ($this->templating->exists($template)) { 
      return $template; 
     } 

     // fallback to built-in twig templates 
     return new TemplateReference('TwigBundle', 'Exception', $name, 'html', 'twig'); 
    } 
} 

Использование: Этот контроллер, а также мои страницы ошибок, существуют в CommonBundle в моем приложении. Вы можете поместить их в любой комплект, который вы хотите, но вам придется настроить функцию ExceptionController::findTemplate, чтобы она смотрела на правильный комплект.

Обратите внимание, что второй аргумент в конструкторе TemplateReference() - это подпапка с ресурсами/представлениями. Так что мои шаблоны ошибок в Rate\CommonBundle\Resources\views\Exception

Symfony DI: Symfony использует twig.controller.exception службы при обработке исключений (см это ссылка здесь: http://symfony.com/doc/current/reference/configuration/twig.html#config-twig-exception-controller), так что это один вам придется переопределить в вашем config.yml

twig.controller.exception: 
    class: %twig.controller.exception.class% 
    arguments: [ "@templating", "@twig", %kernel.debug% ] 

Вы можете видеть, что я впрыскиваю как механизм шаблонов PHP, так и движок ветви.

Вы должны указать свой полный путь к классу в параметрах, а также:

twig.controller.exception.class: Rate\CommonBundle\Controller\ExceptionController 

Это должно сделать это. Надеюсь, это сработает для вас.

Смежные вопросы