Twig 检查数组的元素在另一个数组中

Twig check elements of array are in another array

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

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

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

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

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

有人知道怎么做吗?

使用 for 循环:

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

您可以使用过滤器 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