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?
Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
You can use the yesno filter:
{{ value|yesno:"yeah,no,maybe" }}
You can learn more here
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With