46👍
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.
120👍
- [Django]-Make the first letter uppercase inside a django template
- [Django]-Difference between auto_now and auto_now_add
- [Django]-Retrieving parameters from a URL
30👍
Just because they haven’t been mentioned here yet: the built in template tags default
, and default_if_none
can be useful in simple circumstances:
default
If value evaluates to False, uses the given default. Otherwise, uses the value.
For example:
{{ value|default:"nothing" }}
If value is “” (the empty string), the output will be nothing.
default_if_none
If (and only if) value is None, uses the given default. Otherwise, uses the >value.
Note that if an empty string is given, the default value will not be used. Use >the default filter if you want to fallback for empty strings.
For example:
{{ value|default_if_none:"nothing" }}
If value is None, the output will be the string “nothing”.
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#default
- [Django]-How to limit columns returned by Django query?
- [Django]-How to send a correct authorization header for basic authentication
- [Django]-Django modelform NOT required field
5👍
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.
- [Django]-Difference between filter with multiple arguments and chain filter in django
- [Django]-OperationalError: database is locked
- [Django]-How do I force Django to ignore any caches and reload data?
5👍
I’ve just implemented the ternary operator for Django as a tag, see https://github.com/alexei/django-template-extensions
You can use it as:
{% ?: exp1 exp2 exp3 %}
{% ?: exp1 exp2 %}
Or:
{% iif exp1 exp2 exp3 %}
{% iif exp1 exp2 %}
I figured out that it makes more sense than the yesno
filter, even though it’s really not that Pythonic.
- [Django]-Django: multiple models in one template using forms
- [Django]-Django 2 – How to register a user using email confirmation and CBVs?
- [Django]-Django: Get an object form the DB, or 'None' if nothing matches
3👍
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.
- [Django]-Select distinct values from a table field
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-Celery. Decrease number of processes