【问题标题】:Impossible to access an attribute ("username") on a NULL variable ("")无法访问 NULL 变量 ("") 上的属性 ("username")
【发布时间】:2014-01-27 09:05:08
【问题描述】:

尝试通过put来显示登录用户的用户名

{{ app.user.username }}

在 base.html.twig 中给了我一个类似

的错误
Impossible to access an attribute ("username") on a NULL variable ("") in ::base.html.twig at line 45

像访问它一样

{{ app.security.getToken().getUser().getUsername() }}

导致以下错误。

Impossible to invoke a method ("getUser") on a NULL variable ("") 

如何在 symfony 中全局访问登录用户的属性?如何修复错误?

【问题讨论】:

    标签: symfony


    【解决方案1】:

    尝试先检查用户是否存在,然后获取其用户名:

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

    或使用三元运算符:

    {{ app.user ? app.user.username }} 
    

    如果用户名为空,您可以使用default Twig 过滤器设置默认值:

     {{ app.user.username|default('undefined') }}
    

    【讨论】:

    • 是的..问题是我的'app.user'为空。但我的用户以管理员身份登录。如何找出问题?
    • 知道了!问题是我刷新页面时看到结果不在防火墙后面。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2020-01-05
    • 2017-11-17
    • 2021-11-14
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多