Reputation: 1387
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
Reputation: 1330
you can scan your collection roles of User:
{% for role in app.user.roles %}
{{ role }} <br>
{% endfor %}
Upvotes: 1
Reputation: 1327
You can write a Twig extension to accomplish this.
Create a twig extension and register it as a service.
in services.yml
add
services:
cms.twig.cms_extension:
class: Path\To\RolesTwigExtension.php
tags:
- { name: twig.extension }
arguments: ["@service_container"]
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();
}
}
In your twig file:
<ul>
{% for key, value in app.user|getRoles %}
<li>{{ value.name }}</li>
{% endfor %}
</ul>
Upvotes: 8
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
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
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