Combined logical testing

I have some doubt about how to combine “or” and “and” in an if statement.

If I have either one of two conditions to be met (let’s say Or1 and Or2) and I have 1 condition that should always be met (let’s say And1), and I like to combine these in an if statement, how should I do so?

{% if Or1 or Or2 and And1 %} nor {% if Or1 or And1 or Or2 and And1 %} appear to work correctly, what would be the right way please?

Ward

Hi @Warde

Using a combination of or and and statements is tricky in liquid. There are 2 things about this issue you need to know.

1. You can’t use brackets ( ) to prioritize . It just won’t work when using logic.
2. The logic works from right to the left.
This means that if you for example have following statement: {% if Or1 or Or2 and And1 %}. Liquid will first check Or2 and And1 and then check the last or statement.

Knowing this doesn’t solve all problems though. The best way to address this issue is by using multiple if statements. Let me give you an example to explain this.

{% assign var1 = 200 %}
{% assign var2 = 100 %}
{% assign var3 = 150 %}
{% assign var4 = 250 %}

Let’s say want to check this

{% if (var1 > 150 and var2 > 150) or (var3 > 150 and var4 > 150) %}

as said, you can’t use bracket. That’s why you have to solve it in the following way:

{% if var1 > 150 and var2 > 150)
{% assign check1 = true %}
{% endif %}

{% if (var3 > 150 and var4 > 150)
{% assign check2 = true %}
{% endif %}

{% if check1 == true or check2 == true %}
Do something
{% endif %}

I hope this helps.

Kind regards
Sam

2 Likes