if Tag

Logic Most Useful

Documentation

Conditionals in Django templates work just like they do in Python. The syntax is:

{% if some_conditions %}
  Output this block.
{% elif other_conditions %}
  Output this block.
{% else %}
  Output this block.
{% endif %}

All of the Python comparison and logical operators are available:

Comparison Operators

  • == – Equals.
  • != – Doesn’t equal.
  • > – Is greater than.
  • < – Is less than.
  • >= – Is greater than or equal to.
  • <= – Is less than or equal to.
  • is – Is the same object.
  • is not – Is not the same object.
  • in – Is in a sequence. *Note that the only types of sequences you can create in the template are lists of strings, which you do by comma-separating the values:
    {% if animal in "elephant,giraffe,donkey" %}
    Other sequences must be made available to the template from the view.

Logical Operators

  • and (e.g., if a and b:)
  • or (e.g., if a or b:)
  • not (e.g., if not a:)

Commentary

  1. You must include spaces around the comparison operators.
    {% if a == b or c > d %}
    If you fail to include spaces, you will get a TemplateSyntaxError.
  2. To check for the existence a URL parameter, use:
    {% if request.GET.foo %}
    This will return True if foo is passed on the querystring and has some value.

Did we get something wrong? Is there a use case for the if tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:22 p.m. EST