本文介绍了无法访问 NULL 变量(“")上的属性(“用户名")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试通过put来显示登录用户的用户名
Trying to display the username of the logged in user by putting
{{ app.user.username }}
在 base.html.twig 中给了我一个类似
in base.html.twig gives me an error like
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 中全局访问登录用户的属性?如何修复错误?
How to acess the logged-in user's attributes globally in symfony? How to fix the error?
推荐答案
尝试先检查用户是否存在,然后获取用户名:
Try to check first if user exists, and then get its username:
{% if app.user %}
{{ app.user.username }}
{% endif %}
或使用三元运算符:
{{ app.user ? app.user.username }}
如果用户名为空,您可以使用 default Twig 过滤器来设置默认值:
You could use default Twig filter to set default value if username is empty:
{{ app.user.username|default('undefined') }}
这篇关于无法访问 NULL 变量(“")上的属性(“用户名")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!