If Statement

An if statement evaluates a variable and executes a block of code if the value is true.

Example

 {% if greeting == 1 %}

 <h1>Hello</h1>

{% endif %} 


Elif

The elif keyword says "if the previous conditions were not true, then try this condition".

Example

{% if greeting == 1 %}

  <h1>Hello</h1>

{% elif greeting == 2 %}

  <h1>Welcome</h1>

{% endif %} 


Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

{% if greeting == 1 %}

  <h1>Hello</h1>

{% elif greeting == 2 %}

  <h1>Welcome</h1>

{% else %}

  <h1>Goodbye</h1>

{% endif %} 

Operators

The above examples uses the == operator, which is used to check if a variable is equal to a value, but there are many other operators you can use, or you can even drop the operator if you just want to check if a variable is not empty:

Example

{% if greeting %}

  <h1>Hello</h1>

{% endif %} 


==

Is equal to.

Example

{% if greeting == 2 %}

  <h1>Hello</h1>

{% endif %} 


!=

Is not equal to.

Example

{% if greeting != 1 %}

  <h1>Hello</h1>

{% endif %} 


Is

Django If Else

Login
ADS CODE