PatrickC
PatrickC

Reputation: 101

Django template conditional statement

I have the conditional statement below

{% if juice.slug != "slug-one" or "slug-two" %}
   rendering things if the page slug isn't slug-one or slug-two
{% endif %}

For some reason this conditional statement only works when it isn't "slug-one", instead of when it isn't "slug-one" or "slug-two" .

Upvotes: 1

Views: 525

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Short answer: use if juice.slug != "slug-one" and juice.slug != "slug-two".

The statement juice.slug != "slug-one" or "slug-two" is always True. Python evaluates the truthiness of expressions, and a non-empty string has truthiness True.

You are looking for a condition:

{% if juice.slug != "slug-one" and juice.slug != "slug-two" %}
   rendering things if the page slug isn't slug-one or slug-two
{% endif %}

So you have to repreat the juice.slug != part, and the operator in between is and, not or. If we use or, then the statement is still always True, since:

slug       | slug != "slug-one" |  slug != "slug-two" | with and | with or
--------------------------------------------------------------------------
"slug-one" | False              | True                | False    | True
"slug-two" | True               | False               | False    | True
other      | True               | True                | True     | True

So if you use or, each time at least one of the two statements is True, since if the string is equal to "slug-one", then of course it is not equal to "slug-two" and vice versa.

Upvotes: 1

Related Questions