0

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?

3
  • 3
    IMHO, you should write this logic in view instead of template Commented May 23, 2019 at 4:53
  • 2
    That code can also be shortened to one line: res = ' & '.join(filter(None, [a, b])) Commented May 23, 2019 at 5:02
  • @ruddra I will try it in view. Thanks. Commented May 23, 2019 at 5:48

3 Answers 3

1

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 %}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
res=''
if a !='': 
     if b!='':
          res= a + '&' + b     
     else:
          print('b is empty')
else:
     print('a is empty')

print(res)

if 'res' is empty its print nothing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.