Django Template Ternary Operator

后端 未结 6 833
慢半拍i
慢半拍i 2020-12-29 19:32

I was wondering if there was a ternary operator (condition ? true-value : false-value) that could be used in a Django template. I see there is a python one (true-value if c

6条回答
  •  自闭症患者
    2020-12-29 20:00

    Just because they haven't been mentioned here yet: the built in template tags default, and default_if_none can be useful in simple circumstances:

    default

    If value evaluates to False, uses the given default. Otherwise, uses the value.

    For example:

    {{ value|default:"nothing" }}

    If value is "" (the empty string), the output will be nothing.

    default_if_none

    If (and only if) value is None, uses the given default. Otherwise, uses the >value.

    Note that if an empty string is given, the default value will not be used. Use >the default filter if you want to fallback for empty strings.

    For example:

    {{ value|default_if_none:"nothing" }}

    If value is None, the output will be the string "nothing".

    https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#default

提交回复
热议问题