If I had a user object stored in the session, I could retrieve the user name in twig using somthing like:
app.session.get('user').UserName
But my user object (UserInterface
) resides in the security context, more specifically in the user field of the userToken (TokenInterface) object. How can I access values inside the user object from twig? I am thinking of something along the lines of:
app.security.context.token.user.[my_user_property]
The security context is available from the app
global as security
:
{{ app.security.getToken().getUser() }}
will output the string representation of your user object (or "anon." if you're not logged in, but are authenticated).
Note that unless you have declared public properties, you'll have to use your getter/setter methods:
{{ app.security.getToken().getUser().getUsername() }}
As a shortcut you can use the set
tag to define a user variable in the template:
{% set user = app.security.getToken().getUser() %}
and save yourself a lot of typing, or pass it in from the controller.
In our project, we use the app object
. It's a Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables
This object has a method getUser
to access the user in the security context.
So in your code you can use
{{ app.user.username }}
to retrieve the user in your views.
Just a note, Twig has a feature where you can check if a user has a given role from the view layer:
{% if is_granted('ROLE_USER') %}
<a href="...">Delete</a>
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With