9

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

icedwater
  • 4,701
  • 3
  • 35
  • 50
hendra1
  • 1,359
  • 1
  • 15
  • 24

5 Answers5

30

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 %}
Ivan Gabriele
  • 6,433
  • 5
  • 39
  • 60
8

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>
    
Benoit Duffez
  • 11,839
  • 12
  • 77
  • 125
Praveesh
  • 1,257
  • 1
  • 10
  • 23
4

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 %}
Fabiano Monteiro
  • 401
  • 6
  • 13
1

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

{{ dump(app.security.token.roles) }}
Mohebifar
  • 3,341
  • 1
  • 24
  • 32
  • when I try it why the return value is like this : array (size=0) – hendra1 Jun 24 '14 at 11:16
  • array(1) { [0]=> object(AppBundle\Entity\Role)#1067 (3) { ["id":"AppBundle\Entity\Role":private]=> int(3) ["name":"AppBundle\Entity\Role":private]=> string(5) "admin" ["role":"AppBundle\Entity\Role":private]=> string(10) "ROLE_ADMIN" } } This is my output – Sudhakar Krishnan May 25 '15 at 15:04
  • 1
    app.user.roles is now (3.x) the answer. – RichieHH Sep 20 '17 at 14:14
1

you can scan your collection roles of User:

{% for role in app.user.roles %}
{{ role }} <br> 
{% endfor %}
rapaelec
  • 1,238
  • 12
  • 10