hendra1
hendra1

Reputation: 1387

Symfony2 Get User Role in Twig

I have one question,

How can i get User role in Symfony2 Twig.

I Had looking around but I couldn't find it.

Please help, or clue..

Thanks before.

Hendrawan

Upvotes: 9

Views: 33805

Answers (5)

rapaelec
rapaelec

Reputation: 1330

you can scan your collection roles of User:

{% for role in app.user.roles %}
{{ role }} <br> 
{% endfor %}

Upvotes: 1

Praveesh
Praveesh

Reputation: 1327

You can write a Twig extension to accomplish this.

Create a twig extension and register it as a service.

  1. in services.yml add

    services:
      cms.twig.cms_extension:
        class: Path\To\RolesTwigExtension.php
        tags:
          - { name: twig.extension }
        arguments: ["@service_container"]
    
  2. In RolesTwigExtension.php

    use Symfony\Component\Security\Core\User\UserInterface;
    
    class RolesTwigExtension extends \Twig_Extension {
        public function getFilters() {
            return array(
                new \Twig_SimpleFilter('getRoles', [$this, 'getRoles']),
            );
        }
    
        public function getName() {
            return 'roles_filter_twig_extension';
        }
    
        public function getRoles(UserInterface $user) {
            return $user->getRoles();
        }
    }
    
  3. In your twig file:

    <ul>
        {% for key, value in app.user|getRoles %}
            <li>{{ value.name }}</li>
        {% endfor %}
    </ul>
    

Upvotes: 8

Fabiano Monteiro
Fabiano Monteiro

Reputation: 431

Silex:

{{ dump(app.user.roles) }}
array(1) { [0]=> string(9) "ROLE_USER" }


{% if app.user is not null %}
  {% for role in app.user.roles if role != 'ROLE_ADMIN' %}
      {{ role }} //ROLE_USER
  {% endfor %}
{% endif %}

Upvotes: 4

Ivan Gabriele
Ivan Gabriele

Reputation: 6900

A simpler option could be to test the role since you have to define them in security.yml :

{% if is_granted('ROLE_ADMIN') %}
    Administrator
{% elseif is_granted('ROLE_USER') %}
    User
{% else %}
    Anonymous
{% endif %}

Upvotes: 31

Mohebifar
Mohebifar

Reputation: 3411

You can access the whole security token using app.security.token. Also roles is an attribute of token.

{{ dump(app.security.token.roles) }}

Upvotes: 1

Related Questions