4

Done some searching on this but can't quite find what I'm looking for. Most threads are regarding keys.

I want to know if there is a way to test if a value exists in a twig array.

It should be able to check whether the value is a variable, object or an array.

So for example:

{% if value not in array %}
    .... do someting
{% endif %}

Any suggestions welcome.

6

Like you said, to test if a value exists in a Twig array you'd do:

{% if myValue in ['apples', 'oranges'] %}
    {# do something... #}
{% endif %}

To check whether the value is an array or object you could use the iterable test:

{% if myValue is iterable %}
    {# myValue is an array or object #}
{% else %}
    {# myValue is probably a string #}
{% endif %}

To be certain, you might be best coming out of Twig using a plugin Template Variable and doing it directly in PHP.

  • Thanks @Jamie I think I will need to create a plugin as it's not working on what I require it for. Cheers – Lettie Apr 7 '16 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.