Django Template Ternary Operator


Question

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 condition else false-value) but I'm unsure how to use that inside a Django template to display the html given by one of the values. Any ideas?

1
52
6/24/2010 1:11:24 PM

Accepted Answer

Why would you need a ternary operator within a template? {% if %} and {% else %} are all you need.

Or you could try the firstof tag:

{% firstof var1 var2 var3 %}

which outputs the first one of var1, var2 or var3 which evaluates to a True value.

32
6/24/2010 1:13:33 PM

You can use the yesno filter:

{{ value|yesno:"yeah,no,maybe" }}

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon