获取未登录 TWIG Symfony2 的用户的角色 [英] Get ROLE of a user not logged in TWIG Symfony2

查看:31
本文介绍了获取未登录 TWIG Symfony2 的用户的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当用户不是 twig 中的当前用户时,我如何知道是否已授予该用户.

I would like to know how can i know if a user is granted when it's not the current user in twig.

我为当前用户使用此代码:

I use this code for the current user:

{% if is_granted('ROLE_USER') %}
    <a href="...">Delete</a>
{% endif %}

但我希望能够对目前未登录的其他用户执行相同的操作.谢谢.

But i would like to be able to do the same thing with ohter users that are not logged in at the moment. Thank you.

事实上,我认为 Twig 没有直接的方法来测试未经身份验证的用户的角色.所以我直接在 twig 模板中做了,测试用户是否是管理员,然后设置 var.(在我的问题中,我正在搜索用户列表中的操作方法.)

In fact i think there isn't a direct way with twig to test role of a user that is not authenticated. So i did it directly in the twig template, test if a user is admin or not, then set var. (in my question i was searching how to do in a list of users.)

{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %} 
    {% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
    {% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}

推荐答案

我认为如果您在 User 实体中实现 isGranted 函数会容易得多:

I think it would be much easier if you implemented an isGranted function in the User entity:

Class User implements UserInterface {
    ...
    public function isGranted($role)
    {
        return in_array($role, $this->getRoles());
    }
}

您现在可以轻松检查应用程序每一层中授予的角色.在 PHP 中:

You can now easily check for granted roles in every layer of your application. In PHP:

$user->isGranted("USER_ADMIN")

或者在 Twig 中:

Or in Twig:

user.granted("USER_ADMIN")

如果您需要检查当前用户的角色,您可以在 Twig 中执行此操作:

If you need to check a role for the current user, you can do this in Twig:

app.user.granted("USER_ADMIN")

注意:变量app"是全局定义的.

Note: the variable "app" is globally defined.

注意 2:如果您在应用的安全区域之外使用此代码可能会引发异常,因为 app.user 将为 NULL.

Note 2: this code may throw an exception if you use it outside the secured area of your app, since app.user would be NULL.

这篇关于获取未登录 TWIG Symfony2 的用户的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆