Symfony 2: 如何检查用户是否在模板中登录?

在 Symfony 2模板中(使用 Twig) ,如何有效地检查用户是否未登录?

我不想用 ROLE检查。我想要一个简单的方法来检查用户是否没有登录。

我知道将 app.user.usernameanon进行比较是可行的,但是我就是感觉不对劲。

92405 次浏览

You can check if app.user is set.

 {% if app.user %}
# user is logged in
{% else %}
# user is not logged in
{% endif %}

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.

{% if app.user %}
# user is logged in (any and all users, regardless of ROLE_*)
{% elseif not app.user %}
# user is not logged in (note the `not` in the `elseif` statement)
{% endif %}

Checking authentication status

You can use the is_granted() method to check for ROLES, (The below are all roles assigned by symfony, You may also have you own roles (more below))

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
# This user entered their credentials THIS session
{% elseif is_granted('IS_AUTHENTICATED_REMEMBERED') %}
# User logged in via a cookie (ie: Auth again before doing sensitive things)
{% elseif is_granted('IS_AUTHENTICATED_ANONYMOUSLY') %}
# This is a `guest` or anonymous user
{% endif %}

from the docs:

IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.

IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.

IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.


Checking Roles

You can also use is_granted() to check for roles.
Assuming we have 3 roles (ROLE_SUPER_ADMIN, ROLE_ADMIN, & ROLE_USER)

{% if is_granted('ROLE_SUPER_ADMIN') -%}
# You're `ROLE_SUPER_ADMIN`
{% elseif is_granted('ROLE_ADMIN') -%}
# You're `ROLE_ADMIN`
{% elseif is_granted('ROLE_USER') -%}
# You're `ROLE_USER`
{% else %}
# You're a `nobody` ;P
{%- endif %}

Doing the above inside a controller

View the following answer: How to check if an user is logged in Symfony2 inside a controller?