【问题标题】:Twig check elements of array are in another array数组的树枝检查元素在另一个数组中
【发布时间】:2020-04-02 20:09:26
【问题描述】:

我正在尝试检查一个数组的任何元素是否设置在另一个数组中。 示例:

我有['ROLE_ADMIN','ROLE_MANAGER'] 的user.roles,我有['ROLE_ADMIN','ROLE_USER'] 的product.roles。

我想检查(在 Twig 中)是否有任何 user.roles 在 product.roles 中,例如:

{{ user.roles[0] is product.roles|keys }}

但是 user.roles 的每个元素都在同一个函数中。

有人知道怎么做吗?

【问题讨论】:

    标签: twig


    【解决方案1】:

    您可以使用过滤器filter 来执行此操作,但猜测最好将其移至PHP / TwigExtension

    {% if user.roles |filter((role) => role in product.roles) | length > 0 %}
        Can do something with the post
    {% else %}
        Access denied
    {% endif %}
    

    demo

    【讨论】:

    • 感谢@DarkBee!,这行得通!但最后我做了一个 Symfony Voter 可以在树枝和控制器中使用 is_granted :)。但是您的解决方案也很有效:)
    • 很高兴听到您以这种方式解决了它。你采取的方法比在纯树枝上做的要好得多
    【解决方案2】:

    使用 for 循环:

    {% for role in user.roles %}
      {% if role in product.roles|keys %}
        do something...
      {% endif %}
    {% endfor %}
    

    【讨论】:

    • 如果授予两个或多个角色,您将有多个输出
    猜你喜欢
    • 1970-01-01
    • 2021-01-30
    • 2017-03-03
    • 2010-10-06
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多