This article describes how to use the ifequal and ifnotequal labels in Django. Django is one of the most popular Python frameworks, if you need a friend, you can refer to the Django template system and never thought of implementing a full-featured programming language. Therefore, it does not allow us to execute Python statements in the template (or that sentence, for more information, see concepts and restrictions ). However, comparing the values of two variables and displaying some results is a very common requirement. Therefore, Django provides the {% ifequal %} tag for us to use.
The {% ifequal %} tag compares two values. when they are equal, all values are displayed in {% ifequal %} and {% endifequal %.
The following example compares two template variables: user and currentuser:
{% ifequal user currentuser %} Welcome!{% endifequal %}
The parameter can be a hard-coded string that is caused by single or double quotation marks. the following code is correct:
{% ifequal section 'sitenews' %} Site News{% endifequal %}{% ifequal section "community" %} Community{% endifequal %}
Similar to {% if %}, {% ifequal %} supports the optional {% else %} tag:
{% ifequal section 'sitenews' %} Site News{% else %} No News Here{% endifequal %}
Only Template variables, strings, integers, and decimals can be used as the {% ifequal %} tag parameters. The following is an example of a valid parameter:
{% ifequal variable 1 %}{% ifequal variable 1.23 %}{% ifequal variable 'foo' %}{% ifequal variable "foo" %}
Other types, such as the dictionary type, list type, and Boolean type of Python, cannot be used in {% ifequal %. The following are some examples of errors:
{% ifequal variable True %}{% ifequal variable [1, 2, 3] %}{% ifequal variable {'key': 'value'} %}
To determine whether the variable is true or false, replace {% if %} with {% ifequal % }.