Django Template Ternary Operator

后端 未结 6 834
慢半拍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 19:54

    I've just implemented the ternary operator for Django as a tag, see https://github.com/alexei/django-template-extensions You can use it as:

    {% ?: exp1 exp2 exp3 %}
    {% ?: exp1 exp2 %}
    

    Or:

    {% iif exp1 exp2 exp3 %}
    {% iif exp1 exp2 %}
    

    I figured out that it makes more sense than the yesno filter, even though it's really not that Pythonic.

提交回复
热议问题