【问题标题】:Symfony2 Get User Role in TwigSymfony2 在 Twig 中获取用户角色
【发布时间】:2014-08-14 13:19:45
【问题描述】:

我有一个问题,

如何在 Symfony2 Twig 中获取用户角色。

我四处张望,但找不到。

请帮忙,或者线索..

之前谢谢。

亨拉万

【问题讨论】:

  • 你使用像 FOSUserBundle 这样的捆绑软件吗?
  • 不,我使用 symfony 基本安全
  • 您可以在此处找到回复。 stackoverflow.com/questions/7463650/…
  • 您想获取 1 个用户的角色列表吗?如果您只想测试一个角色,请参阅@IvanGabriele 答案。你使用群组吗?

标签: symfony twig user-roles


【解决方案1】:

一个更简单的选择可能是测试角色,因为您必须在 security.yml 中定义它们:

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

【讨论】:

    【解决方案2】:

    您可以编写一个 Twig 扩展来完成此操作。

    创建一个 twig 扩展并将其注册为服务。

    1. services.yml添加

      services:
        cms.twig.cms_extension:
          class: Path\To\RolesTwigExtension.php
          tags:
            - { name: twig.extension }
          arguments: ["@service_container"]
      
    2. 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. 在你的树枝文件中:

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

    【讨论】:

      【解决方案3】:

      西莱克斯:

      {{ 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 %}
      

      【讨论】:

        【解决方案4】:

        您可以使用app.security.token 访问整个安全令牌。 roles也是token的一个属性。

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

        【讨论】:

        • 当我尝试它时为什么返回值是这样的:array (size=0)
        • array(1) { [0]=> object(AppBundle\Entity\Role)#1067 (3) { ["id":"AppBundle\Entity\Role":private]=> int (3) ["name":"AppBundle\Entity\Role":private]=> 字符串(5) "admin" ["role":"AppBundle\Entity\Role":private]=> 字符串(10) "ROLE_ADMIN " } } 这是我的输出
        • app.user.roles 现在 (3.x) 是答案。
        【解决方案5】:

        您可以扫描用户的收藏角色:

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

        【讨论】:

          猜你喜欢
          • 2012-02-23
          • 2012-06-30
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 2011-09-02
          • 1970-01-01
          • 1970-01-01
          • 2015-11-06
          相关资源
          最近更新 更多