简体   繁体   中英

Symfony 2 - Accessing Hierarchical Roles in a twig template

In my template, I need to know if a user has certain role to display things according to it. So far, I've implemented a little function in my user class:

  public function hasRole($role) {
    $roles = array();
    foreach ($this->getRoles() as $rol) {
      $roles[] = $rol->getRole();
    }
    return in_array($role, $roles);
  }

which tells me if this user has the role specified by the string passed as a parameter. This work and can be called from a twig template, but doesn't allow me to know anything about the roles hierarchy. Is there a way to access the role hierarchy from a controller? and directly from a twig template? I've looked through the official docs and didn't find anything about.

You can check the roles in twig templete by using below code,It explains that if the current user has the below role,then show something

{% if is_granted('ROLE_ADMIN') %}

  //show things related to admin role

{%else if is_granted('ROLE_USER')%}
//show things related to user role
{% endif %}

Hope this helps you. Happy Coding!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM