Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 527
Throoze Avatar asked Apr 21 '12 04:04

Throoze


1 Answers

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!!

like image 84
Asish AP Avatar answered Oct 14 '22 14:10

Asish AP