5

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.

2 Answers 2

9

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.

1
  • 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, 2016 at 10:01
1

Craft 3.7.15 onwards you can use is array twig test. More info https://github.com/craftcms/cms/blob/develop/CHANGELOG.md

1

Your Answer

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

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