Django Triple Template Template Operator

I was wondering if there is a triple operator (condition? True-value: false-value) that can be used in a Django template. I see that there is python one (true-value if condition else false-value), but I'm not sure how to use this inside the Django template to display the html given by one of the values. Any ideas?

+42
python ternary-operator django templates
Jun 24 '10 at 13:05
source share
6 answers

Why do you need a three-dimensional operator in a template? {% if %} and {% else %} are all you need.

Or you can try the firstof tag:

 {% firstof var1 var2 var3 %} 

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

+25
Jun 24 '10 at 13:13
source share
โ€” -

You can use yesno filter:

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

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

+58
May 22 '11 at 16:37
source share

Just because they have not been mentioned here yet: the built-in template tags default and default_if_none can be useful in simple circumstances:

default

If the value is False, the specified default value is used. Otherwise, the value is used.

For example:

{{ value|default:"nothing" }}

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

default_if_none

If (and only if) the value is None, the default setpoint is used. Otherwise, the value> is used.

Please note that if an empty string is specified, the default value will not be used. Use> the default filter if you want to back out for empty lines.

For example:

{{ value|default_if_none:"nothing" }}

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

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

+9
Mar 11 '16 at 2:17
source share

No. Django's tempatetag pattern {% if %} just started supporting == , and etc. {% if cond %}{% else %}{% endif %} as compact as possible.

+3
Jun 24 '10 at 13:15
source share

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

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

Or:

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

I realized that this makes more sense than a yesno filter, although it really is not that Pythonic.

+3
Oct 10
source share

I wonder if python and / or the trick works?

 condition and true_value or false_value 

behaves like a ternary operator - displays true_value if the condition is True, and false_value if not.

+1
Jun 24 '10 at 14:29
source share



All Articles