H.W.
H.W.

Reputation: 353

Get username in Symfony (in Twig) on page, which is accessible to anonymous users

Is there a way to access username of the logged user on page, which is accessible to anonym users in Symfony 2.6.1?

Example: I have main page, where is link to login and if there is a user logged in, I want to display his username as a link to his account instead of the login link.

If I use {{ app.user.username }} it will display error

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

because app.user is null object on pages with security: false defined is security.yml. It will work only on pages, which needs to be under firewall with no security: false.

Upvotes: 0

Views: 1273

Answers (3)

Gustek
Gustek

Reputation: 3760

Try this

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

Upvotes: 0

BENARD Patrick
BENARD Patrick

Reputation: 30975

You should try something like this:
set a default value for anonymous :

{{ app.user.username|default('Not Logged') }}

Upvotes: 0

4lxndr
4lxndr

Reputation: 317

Im not sure if i understood your problem correctly, but its true that {{ app.user.username }} throws an exception, because there is not user object if you are not logged in. So just check if the object exists:

{% if app.user is defined %}
    {# link to account #} 
{% else %}
    {# link to login #}
{% endif %}

If this hint is not the exspected one, give us some code.

Upvotes: 0

Related Questions