I have two string variables that I want to display on a Django template. If variable a is empty, do not display it. Similar with b. But if a and b are both non-empty, then concatenate the two strings with a ' & '.
Here's the logic in Python.
res = ''
if a != '':
res = a
if b != '':
if res == '':
res = b
else:
res = res + ' & ' + b
print(res)
How would I write this logic into a Django template?
you should write this logic in view as the comment of @ruddra, but if you adhere to use django template, you can try this:
{% if a == ' ' %}
{% if b == ' ' %}
res = ''
{% else %}
res = {{b}}
{% endif %}
{% else %}
{% if b == ' ' %}
res = {{a}}
{% else %}
res = {{a}} & {{b}}
{% endif %}
{% endif %}
As others have pointed out, it's easier to write this in your view instead of template .
If you really want to:
{% if a != '' and b != '' %}
{{ a }}&{{ b }}
{% elif a != '' and b == '' %}
{{ a }}
{% elif a == '' and b != '' %}
{{ b }}
{% else %}
{# You didn't mention #}
{% endif %}
res=''
if a !='':
if b!='':
res= a + '&' + b
else:
print('b is empty')
else:
print('a is empty')
print(res)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.