In Symfony 2 templates (using Twig), how can I effectively check whether a user is not logged in?
I don't want to use ROLE
checks. I want a straightforward way to check if a user is not logged in.
I'm aware that comparing app.user.username
with anon
works, but that just doesn't feel right to me.
You can check if app.user is set.
Although the current answer answers the OP's question, I would like to add more details.
I understand the OP did not want to check roles, but I am including them so other SO users can copy and paste from this in the future. - everytime I google this, I end up here!
Symfony Doc Sources:
Check if any user logged in (regardless of role)
As answered, you can use
app.user
to check if any user is logged in.Checking authentication status
You can use the
is_granted()
method to check forROLES
, (The below are all roles assigned by symfony, You may also have you own roles (more below))from the docs:
Checking Roles
You can also use
is_granted()
to check for roles.Assuming we have 3 roles (
ROLE_SUPER_ADMIN
,ROLE_ADMIN
, &ROLE_USER
)Doing the above inside a controller
View the following answer: How to check if an user is logged in Symfony2 inside a controller?