Почему Symfony 4 не загружает функции Twig при обнаружении ошибок, которые существуют при обычном вызове страницы - PullRequest
0 голосов
/ 28 декабря 2018

У меня есть платформа Symfony 4.2, и я пытаюсь создать собственный шаблон ошибки на основе базового шаблона приложения.

Мой шаблон по умолчанию имеет следующий код в 'Default / template.html.twig':

{% trans_default_domain "messages" %}

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>{% block title %}{{ 'Gibbon - Mobile'|trans }}{% endblock title %}</title>

        {% block stylesheets %}
        {% endblock stylesheets %}
    </head>
    <body>
    <div class="container mobileContent">
        {% block titleBar %}
            <div id="titleBar">
                <h2 class="alert alert-success text-center">{{ title|default('Gibbon - Mobile')|trans }}
                    <div style="float: left;">{{ miscButton({title: 'Home', style: 'margin-top: -0.6rem;', class: 'btn btn-transparent alert-success fas fa-home fa-fw fa-2x', windowOpen: {route: path('home')}})|raw }}
                    </div>
                    {% block menuContent %}
                        <div id="notificationTray" style="float: right;"></div>
                    {% endblock menuContent %}
                </h2></div>
        {% endblock titleBar %}
... 

... (дополнительный контент удален.)

Проблема возникает, когда функция miscButton вызывается в ExceptionController при рендеринге шаблона Error / connection_exception.html.twig:

<?php
namespace App\Controller;

use Doctrine\DBAL\Exception\ConnectionException;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController as ExceptionControllerBase;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

/**
 * Class ExceptionController
 * @package App\Controller
 */
class ExceptionController extends ExceptionControllerBase
{
    /**
     * 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.
     *
     * @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();

        if (ConnectionException::class === $exception->getClass()) {
            return new Response($this->twig->render(
                'Error/connection_exception.html.twig',
                [
                    'status_code' => $code,
                    'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
                    'exception' => $exception,
                    'logger' => $logger,
                    'currentContent' => $currentContent,
                ]
            ), 200, ['Content-Type' => $request->getMimeType($request->getRequestFormat()) ?: 'text/html']);
        } else
            return new Response($this->twig->render(
                (string) $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,
                )
            ), 200, array('Content-Type' => $request->getMimeType($request->getRequestFormat()) ?: 'text/html'));
    }
}

, который является тольковызывается, когда встречается исключение.Это было установлено в служебном файле для ветки в качестве контроллера исключений:

twig:
    ...
    exception_controller: App\Controller\ExceptionController::showAction

Шаблон ветки 'Error / connection_exception.html.twig':

{% trans_default_domain "messages" %}

{% extends 'Default/template.html.twig' %}

{% set title = 'Connection Exception' %}

{% block content %}
    <div class="container">
        {{ dump() }}
    </div>
{% endblock content %}

Система выдаетTwig_Error_Syntax из: Twig_Error_Syntax Неизвестная функция "miscButton".

in template.html.twig line 17
at Twig_ExpressionParser->getFunctionNodeClass('miscButton', 17)
in ExpressionParser.php line 367
at Twig_ExpressionParser->getFunctionNode('miscButton', 17)
in ExpressionParser.php line 152
at Twig_ExpressionParser->parsePrimaryExpression()
in ExpressionParser.php line 92
at Twig_ExpressionParser->getPrimary()
in ExpressionParser.php line 45
at Twig_ExpressionParser->parseExpression()
in Parser.php line 125
at Twig_Parser->subparse(array(object(Twig_TokenParser_Block), 'decideBlockEnd'), true)
in Block.php line 38
at Twig_TokenParser_Block->parse(object(Twig_Token))
in Parser.php line 168
at Twig_Parser->subparse(null, false)
in Parser.php line 81
at Twig_Parser->parse(object(Twig_TokenStream))
in Environment.php line 533
at Twig_Environment->parse(object(Twig_TokenStream))
in Environment.php line 565
at Twig_Environment->compileSource(object(Twig_Source))
in Environment.php line 368
at Twig_Environment->loadTemplate('Default/template.html.twig', null)
in Template.php line 330
at Twig_Template->loadTemplate('Default/template.html.twig', 'Error/connection_exception.html.twig', 3)
in 8039d13d7f19bf3be65e86c362558a70fd97574adf50f4ff5ebd74542210f233.php line 15
at __TwigTemplate_da37c7d18d4bfb02766acd7d18a05f51739a25a6224cafdd1b0abb0753679771->__construct(object(Twig_Environment))
in Environment.php line 397
at Twig_Environment->loadTemplate('Error/connection_exception.html.twig')
in Environment.php line 289
at Twig_Environment->render('Error/connection_exception.html.twig', array('status_code' => 500, 'status_text' => 'Internal Server Error', 'exception' => object(FlattenException), 'logger' => object(Logger), 'currentContent' => ''))
in ExceptionController.php line 73
at ExceptionController->showAction(object(Request), object(FlattenException), object(Logger))
in HttpKernel.php line 150

Эта ошибка NOT возникает, когда ошибка не вызвала перенаправление.Функция miscButton показана в команде debug: twig

php bin/console debug:twig

Functions
---------

 ...
 * max(args)
 * min(args)
 * miscButton(details = [])
 ...

Класс расширения, который создает функцию, находится в комплекте поставщика, который я также написал.

Так почему функция не появляется в шаблоне ошибки, а в других случаях отображается правильно?

Спасибо за любую помощь.Craig

...