11

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?

1 Answer 1

28

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') }}
Sign up to request clarification or add additional context in comments.

2 Comments

yes..the problem is my 'app.user' is null.But my user is logged in as admin.How to figure out the issue?
Got it! The problem was the page i was refreshing to see the result was not behind the firewall.Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.