简体   繁体   中英

Impossible to access an attribute (“username”) on a NULL variable (“”)

Trying to display the username of the logged in user by putting

{{ app.user.username }}

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

Acessing it like

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

results in the following error.

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

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 %}

or do it with ternary operator:

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

You could use default Twig filter to set default value if username is empty:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM