Get ROLE of a user not logged in TWIG Symfony2

后端 未结 4 1005
陌清茗
陌清茗 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 20:09

    You should create either a twig macro, or a twig function.

    Creating a macro is very simple, using your code:

    {% macro admin_status(from_user) %}
      {% 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 %}
    {% endmacro %}
    

    You can then use it in the same file as {% _self.admin_status(user) %}. You may also move it to a separate file, and use twig's import tag to gain access to it.

    Creating a twig function is a better option, for details see extending twig. It boils down to creating a regular function, that may be called from twig, so code like this becomes possible:

    {% if user_is_admin(user) %}
    

    You'll also need to read enabling custom twig extensions.

提交回复
热议问题