在Symfony 2模板中(使用Twig),如何有效地检查用户是否未登录?
我不想使用ROLE
支票。我想要一种直接的方法来检查用户是否未登录。
我知道将app.user.username
与anon
进行比较有效,但这对我来说感觉不对。
答案 0 :(得分:186)
您可以检查是否设置了app.user.
{% if app.user %}
# user is logged in
{% else %}
# user is not logged in
{% endif %}
答案 1 :(得分:89)
虽然目前的答案回答了OP的问题,但我想补充更多细节。
我理解OP不想检查角色,但我将其包含在内,以便其他SO用户可以在将来复制和粘贴。 - 每次我谷歌这个,我最终来到这里!
Symfony Doc来源:
如上所述,您可以使用app.user
检查是否已登录任何用户。
{% 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 %}
您可以使用is_granted()
方法检查ROLES
,(以下是symfony分配的所有角色,您可能还拥有自己的角色(详情如下) )
{% 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 %}
来自文档的:
IS_AUTHENTICATED_ANONYMOUSLY - 自动分配给用户 在受防火墙保护的网站部分,但实际上并没有 登录。只有在允许匿名访问的情况下才可以使用。
IS_AUTHENTICATED_REMEMBERED - 自动分配给曾经的用户 通过记住我的cookie验证。
IS_AUTHENTICATED_FULLY - 自动分配给拥有的用户 在当前会话期间提供了他们的登录详细信息。
您还可以使用is_granted()
来检查角色
假设我们有3个角色(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 %}
查看以下答案:How to check if an user is logged in Symfony2 inside a controller?