ShrockCo
ShrockCo

Reputation: 387

If Statement in Timber/Twig not working for me

So if I have a {% if post.product_status != 'In Stock' or 'In Transit' %} {# execute my code #} {% endif %} what would this not be working is there something wrong with me using the or operator? What should I be using instead?

Upvotes: 0

Views: 1109

Answers (1)

Ihar Aliakseyenka
Ihar Aliakseyenka

Reputation: 14213

Your statement will always return true because of In Transit - it is non-empty string.

You may test it

{% if 'In Transit' %}
    // Will be executed
{% endif %}

{% if false or 'In Transit' %}
    // Will be executed because one of condition is true
{% endif %}

{% if post.product_status != 'In Stock' or post.product_status != 'In Transit' %}
    // Will be executed. Why? Even if your status is not 'In Stock' second part of condition will return true
{% endif %}

{% if post.product_status != 'In Stock' and post.product_status != 'In Transit' %}
    // Will NOT be executed if status is 'In Stock' or 'In Transit'. Both conditions are false now
{% endif %}

This condition became quite unreadable so it is better to change it to. Let's check does our status value present in an array of excluded statusses

{% set excluded = [ 'In Stock', 'In Transit', 'Any New Status Here' ] %}

{% if post.product_status not in excluded %}
    // Code to execute
{% endif %}

Upvotes: 1

Related Questions