Get ROLE of a user not logged in TWIG Symfony2

后端 未结 4 1009
陌清茗
陌清茗 2020-12-14 19:28

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_gran         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-14 19:57

    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());
        }
    }
    

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

    $user->isGranted("USER_ADMIN")
    

    Or in Twig:

    user.granted("USER_ADMIN")
    

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

    app.user.granted("USER_ADMIN")
    

    Note: the variable "app" is globally defined.

    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.

提交回复
热议问题