I want to display something like that:
Case 1: “logged in as USER”
@ UserName [ logout ]
No problems here, i just do:
@ {{ app.user.username}} [ <a href=”{{ path(“logout”) }}”>logout</a> ]
Case 2: “logged in as ADMIN”
@ AdminName [ logout ]
The same works here:
@ {{ app.user.username}} [ <a href=”{{ path(“logout”) }}”>logout</a> ]
Case 3: “logged in as ADMIN impersonating a USER”
AdminName @ UserName [ return ]
Now thats a problem:
{{ ??..what here..?? }} @ {{ app.user.username}} [ <a href=”{{ (app.request.getRequestUri ~ ‘?_switch_user=_exit’) }}”>return</a> ]
This is the only solution I know… it seems a lot of code for a sipmle displaying username :/
{# iterating through user roles to find ROLE_PREVIOUS_ADMIN #}
{% for role in app.security.token.roles %}
{% if role.source is defined %}
{{ role.source.user.username }}
{% endif %}
{% endfor %}
@ {{ app.user.username }} [ <a href="{{ (app.request.getRequestUri ~ '?_switch_user=_exit') }}">return</a> ]
Is there any other way? I need a pure TWIG solution -> this is supposed to be part of my main twig template (that is extended by all other templates) -> I can’t add controller code to all actions, just to display username.
With the idea you have proposed above,.. can you not just create a custom twig extension that encompasses your logic from your twig template so that you can just call
myCustomTwigFunctionwithin your twig template and it will output the original users name?See http://symfony.com/doc/current/cookbook/templating/twig_extension.html for more info about custom twig extensions
The code you’d have in your Twig extension file would be…
Where $container is a class variable of the DI Container on your twig extension class