Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Ternary Operator

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?

like image 652
Anon Avatar asked Jun 24 '10 13:06

Anon


People also ask

What is Jinja template in Django?

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.

What does {% %} mean in Django?

{% %} 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.

What is ?: In Python?

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.

How do you use three conditions in a ternary operator?

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.


2 Answers

You can use the yesno filter:

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

You can learn more here

like image 189
jeroenp Avatar answered Oct 24 '22 03:10

jeroenp


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.

like image 36
Daniel Roseman Avatar answered Oct 24 '22 03:10

Daniel Roseman