在页面上获取Synfomy(在Twig中)的用户名,匿名用户可以访问该用户名

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.

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

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

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.

Try this

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