If template tag
Posted: March 4th, 2010 | Author: Davo | Filed under: Django | Tags: if, if tag, smart if, template tag | No Comments »Since 1.2 the {% if %} template tag has become more convenient and smart.
It is now possible to have proper comparison and also combine multiple conditions at the same time.
The boolean operators which are supported are the following :
# equals
{% if name == 'davo' %}
The '{{ name }}' equals to 'davo'
{% endif %}
# different
{% if name != 'davo' %}
The {{ name }} is different from 'davo'
{% endif %}
# lower than
{% if count < 50 %}
{{ count }} is less than 50
{% endif %}
# greater than
{% if count > 50 %}
{{ count }} is more than 50
{% endif %}
# lower or equals than
{% if count <= 100 %}
{{ count }} is less or equal than 100
{% endif %}
# greater or equals than
{% if count >= 100 %}
{{ count }} is equal or more than 100
{% endif %}
# in (similar to python's 'in' keyword)
{% if 'davo' in 'my name is davo' %}
your name is davo
{% endif %}
# assuming that fruits is a list/tuple...
{% if 'apple' in fruits %}
apple is a fruit.
{% endif %}
It is also possible to have multiple conditions using the OR and AND operators.
{% if a > 10 and a < 20 %}
{{ a }} is bigger than 10 and smaller than 20.
{% endif %}
You can negate a condition with the ‘not‘ operator
{% if not a == 10 %}
{{ a }} is different than 10
{% endif %}
Another cool feature is the ability to combine the filtering with the variables:
{% if some_long_text|length > 400 %}
{{ some_long_text }} is too long to display!
{% endif %}
You cannot use () (brackets) to combine the operations but instead you can follow the precedence of the operators which are the following:
- or
- and
- not
- in
- ==, !=, <, >,“<=“, >=
For full details about the new {% if %} tag please have a look at the django docs.
