2

I want to check if there is a number less than 10 in an array.

{% if 10 in [0, 30, 50, 10, 9, 200]  %}
  {# checks only if there is a 10 in it. not if there is anything below 10. #}
   yep. there is a number 10
{% endif %}

That's close, but I want to find find out if there is any number below 10 in it, disregarding how many.

Not possible: {% if 10 > in [0, 30, 50, 10, 9, 200] %}

Also not possible: {% if > 10 in [0, 30, 50, 10, 9, 200] %}

3

Twig isn't very well equipped to deal with more than basic logic and comparisons, but you can accomplish some of these tests with a bit of extra juggling:

{% set constraintMet = false %}

{% for value in [0, 30, 50, 10, 9, 200] %}
  {# Here’s where you get to set up your advanced comparison criteria: #}
  {% if not constraintMet and value < 10 %}
    {% set constraintMet = true %}
  {% endif %}
{% endfor %}

Constraint {{ constraintMet ? "was" : "wasn't" }} met.

Alternatively, you can build the conditional into your for loop…

{% set constraintMet = false %}

{% for value in [0, 30, 50, 10, 9, 200] if not constraintMet and value < 10 %}
  {% set constraintMet = true %}
{% endfor %}

Constraint {{ constraintMet ? "was" : "wasn't" }} met.

…but this is a little more difficult to read, in my opinion, as it obscures the critical test. One improvement this offers, though, is that it prevents the loop from running after the constraint is met, unlike the first option, which runs/renders the body of the if block for every element in the array—even if it finds a match early on.

Whenever possible, I'd recommend stashing this kind of logic in a custom Twig extension. If you haven't built a plugin or module before, Pluginfactory can set you down the right path!

Heads up! map, filter, and reduce functions have come to Twig (and Craft, as of 3.2), which make this possible to collapse this into a one-line statement: {% set hasMatchingValue = [0, 30, 50, 10, 9, 200] | filter(v => v < 10) | length > 0 %}. This just iterates over the array, and filters out anything that is 10 or greater with the implicitly returned value from the “arrow function,” then checks if the new array includes “more than zero” values.

| improve this answer | |
  • thanks. I always want to look into how to build extensions. but then daily business happens :( – KSPR Jun 28 '19 at 8:51

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.