views:

121

answers:

3

Hi, 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?

+3  A: 

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.

Daniel Roseman
I suppose you're right, I'll just use if/else. Just addicted to ternary I guess.
William
+1  A: 

You don't. The Django {% if %} templatetag has only just started supporting ==, and, etc. {% if cond %}{% else %}{% endif %} is as compact as it gets for now.

Oli
A: 

I wonder if the python and/or trick would work?

condition and true_value or false_value

behaves a like the ternary operator - outputs true_value if condition evaluates to True, and false_value if not.

http://diveintopython.org/power_of_introspection/and_or.html

hwjp