Django templates: If false?

后端 未结 10 1151
灰色年华
灰色年华 2020-12-23 14:43

How do I check if a variable is False using Django template syntax?

{% if myvar == False %}

Doesn\'t seem to work.

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 15:06

    In old version you can only use the ifequal or ifnotequal

    {% ifequal YourVariable ExpectValue %}
        # Do something here.
    {% endifequal %}
    

    Example:

    {% ifequal userid 1 %}
      Hello No.1
    {% endifequal %}
    
    {% ifnotequal username 'django' %}
      You are not django!
    {% else %}
      Hi django!
    {% endifnotequal %}
    

    As in the if tag, an {% else %} clause is optional.

    The arguments can be hard-coded strings, so the following is valid:

    {% ifequal user.username "adrian" %} ... {% endifequal %} An alternative to the ifequal tag is to use the if tag and the == operator.

    ifnotequal Just like ifequal, except it tests that the two arguments are not equal.

    An alternative to the ifnotequal tag is to use the if tag and the != operator.

    However, now we can use if/else easily

    {% if somevar >= 1 %}
    {% endif %}
    
    {% if "bc" in "abcdef" %}
      This appears since "bc" is a substring of "abcdef"
    {% endif %}
    

    Complex expressions

    All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

    • or
    • and
    • not
    • in
    • ==, !=, <, >, <=, >=

    More detail

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/

提交回复
热议问题