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

后端 未结 1 1894
野趣味
野趣味 2021-01-12 00:16

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

{{ app.user.username }}

in base.html.twig gives me an error like



        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 00:46

    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') }}
    

    0 讨论(0)
提交回复
热议问题