0

I'm trying to check in twig if any element of one array are set in other array. Example:

I have user.roles with ['ROLE_ADMIN','ROLE_MANAGER'] and I have the product.roles with ['ROLE_ADMIN','ROLE_USER'].

I want to check (in Twig) if any user.roles are in product.roles, like:

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

But with each element of user.roles in the same function.

Does anyone know how?

2 Answers 2

4

You could use the filter filter to do this, but guessing it would be better to move this to PHP / TwigExtension

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

demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @DarkBee!, that works! But finally I make a Symfony Voter to can use the is_granted in twig and in the controller :). But your solution works so well too :)
Glad to hear you solved it this way. The aproach you took is a far better one than doing this in pure twig
0

Use a for loop:

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

1 Comment

If two or more roles are granted you would have multiple output with this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.