How can I access the security context token from the view layer in symfony 2?
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 c开发者_如何学运维an 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 %}
精彩评论