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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With