我正在尝试自定义 Symfony 中的错误页面。
这是我的
error.html.twig
文件,位于 app/Resources/TwigBundle/views/Exception/
:
{% extends '::base.html.twig' %}
{% block body %}
<h1>{{ status_code }}: {{ status_text }}</h1>
{% endblock %}
不幸的是我收到以下错误消息:
致命错误:未捕获的异常 'Symfony\Component\Routing\Exception\ResourceNotFoundException' 中 [...] 供应商\symfony\symfony\src\Symfony\Component\HttpKernel\EventListener\RouterListener.php 144号线
当我删除
{% extends '::base.html.twig' %}
时,一切正常。有什么想法如何将我的基本模板包含在错误页面中吗?
编辑1: 奇怪的是,当抛出 403 时,它似乎起作用,例如,当我访问
/user
但没有必要的权限时。
编辑2: 我将
base.html.twig
的全部内容粘贴到 error.html.twig
文件中,并注意到错误是由于 KnpMenuBundle
包渲染的菜单引起的:
{{ knp_menu_render('ACMEMemberBundle:Builder:mainMenu', { 'style': 'pills', 'currentClass': 'active' }) }}
当我删除这条线时,一切正常。但这不是我想要走的路。无法保留导航吗?
文件应位于
app/Resources/views/Exception/
而不是
app/Resources/TwigBundle/views/Exception/
您是否将页面放在以下位置?
/app/ResourceS/TwigBundle/views/Exception/error404.html.twig
{% extends '::base.html.twig' %}
{% block content %}
{%trans%}errors.404{%endtrans%}
{% endblock %}
// app/Resouces/views/base.html.twig
×
{% include('path/to/include') %}
○
{% include('::path/to/include') %}
我终于完成了将整个代码(基本+当前)放在同一个“error.html.twig”文件中。
它对我有用,避免了巨大的头痛。
请删除第一行中的 :: https://symfony.com/doc/current/templatating.html
{% extends 'base.html.twig' %}
{% block body %}
<h1>{{ status_code }}: {{ status_text }}</h1>
{% endblock %}
我发现这个问题没有公认的答案。但这个问题的答案在mark.sagikazar原帖下的评论中。
如果你的error404在你输入后崩溃了
{% extends 'base.html.twig' %}
进入你的 error404.html.twig,错误提示:
Symfony\Bridge\Twig\Extension\RoutingExtension::getPath(): Argument #1 ($name) must be of type string, null given, called in
那么问题就出在base.html.twig上。就我而言,是
app.request.attributes.get('_route')
因为就像mark.sagikazar所说,错误404或其他错误消息中没有路由。
所以我只是在这段代码周围放置一个 if 语句,如下所示:
{% if app.request.attributes.get('_route') %}
.. do something here that doesnt work in error404.html twig
{% endif %}