无法访问NULL变量("")上的属性("用户名")

Den*_*G B 8 symfony

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

{{ app.user.username }}
Run Code Online (Sandbox Code Playgroud)

在base.html.twig给我一个错误

Impossible to access an attribute ("username") on a NULL variable ("") in ::base.html.twig at line 45
Run Code Online (Sandbox Code Playgroud)

接受它就像

{{ app.security.getToken().getUser().getUsername() }}
Run Code Online (Sandbox Code Playgroud)

导致以下错误.

Impossible to invoke a method ("getUser") on a NULL variable ("") 
Run Code Online (Sandbox Code Playgroud)

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

Vic*_*sky 23

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

{% if app.user %}
    {{ app.user.username }} 
{% endif %}
Run Code Online (Sandbox Code Playgroud)

或者使用三元运算符:

{{ app.user ? app.user.username }} 
Run Code Online (Sandbox Code Playgroud)

如果username为空,您可以使用默认的 Twig过滤器来设置默认值:

 {{ app.user.username|default('undefined') }}
Run Code Online (Sandbox Code Playgroud)