gpt4 book ai didi

twig - Symfony:在 404 错误页面中获取登录用户

转载 作者:行者123 更新时间:2023-12-02 00:43:07 24 4
gpt4 key购买 nike

我正在尝试获取 404 错误页面中登录用户的用户名,例如 symfony docs说;

{# app/Resources/TwigBundle/views/Exception/error404.html.twig #}
{% extends 'base.html.twig' %}

{% block body %}
<h1>Page not found</h1>

{# example security usage, see below #}
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
IS_AUTHENTICATED_FULLY: {{ app.user.username }}
{% endif %}

{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}
IS_AUTHENTICATED_REMEMBERED: {{ app.user.username }}
{% endif %}

{% if app.user %}
app.user: {{ app.user.username }}
{% endif %}

<p>
The requested page couldn't be located. Checkout for any URL
misspelling or <a href="{{ path('homepage') }}">return to the homepage</a>.
</p>
{% endblock %}

在开发中一切正常,但在生产中用户始终未登录。每个 if 条件都失败。

this discussion我发现了这个:

The cause of this problem is that routing is done before security. If a 404 error occurs, the security layer isn't loaded and thus

那么...可以在twig异常页面中获取登录用户吗?

更新

看起来这是一个理想的行为:https://github.com/symfony/symfony/issues/8414#issuecomment-23661839

这个hack可以“解决”,但它真的很丑......

最佳答案

到目前为止我找到的唯一解决方案是:

routing.yml(这必须是最后一条规则)

pageNotFound:
pattern: /{path}
defaults: { _controller: MyContentBundle:PageNotFound:pageNotFound, path: '' }
requirements:
path: .*

Controller 操作

public function pageNotFoundAction()
{
throw new NotFoundHttpException();
}

Reference

希望能找到更好的解决方案

关于twig - Symfony:在 404 错误页面中获取登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38499779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com