Django templates: If false?

后端 未结 10 1099
灰色年华
灰色年华 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条回答
  • 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/

    0 讨论(0)
  • 2020-12-23 15:11

    Look at the yesno helper

    Eg:

    {{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
    
    0 讨论(0)
  • 2020-12-23 15:15

    Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

    For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

    {% if test.passed|lower == 'false' %} ... {% endif %}
    

    Or if you prefer getting excited over the whole thing...

    {% if test.passed|upper == 'FALSE' %} ... {% endif %}
    

    Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

    0 讨论(0)
  • 2020-12-23 15:17

    You could write a custom template filter to do this in a half-dozen lines of code:

    from django.template import Library
    
    register = Library()
    
    @register.filter
    def is_false(arg): 
        return arg is False
    

    Then in your template:

    {% if myvar|is_false %}...{% endif %}
    

    Of course, you could make that template tag much more generic... but this suits your needs specifically ;-)

    0 讨论(0)
提交回复
热议问题