Symfony 2 - Access hierarchical roles in a branch template

In my template, I need to know if the user has a specific role to display things according to him. So far I have implemented a small 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 indicated by the string passed as a parameter. This work can be called from the branch template, but it does not allow me to know anything about the hierarchy of roles. Is there a way to access the role hierarchy from the controller? and directly from the twig template? I looked through the white papers and found nothing.

+8
php symfony twig roles
source share
1 answer

You can check the roles in twig templete using the code below. He explains that if the current user has the following 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!

+19
source share

All Articles