Kelvin Barsana
Kelvin Barsana

Reputation: 864

Python HTML template ternary operator

I've come across with different python ternary operators such as:

a if b else 0

but it didn't work when I tried to include it inside Django HTML template

{% a if b else 0 %}

Here is the exact code that I'll be using but won't work:

{% 'error' if form.title.errors else '' %}

or

{% form.title.errors ? 'error' : '' %}

I don't like to do the usual

{% if form.title.errors %}error{% endif %}

because it looks bulky in my opinion especially if I add an else statement.

Any suggestions? or should I just stick with it?

Upvotes: 1

Views: 2677

Answers (2)

javimuu
javimuu

Reputation: 1859

In Django, the templatetags just support {% if %}{% else %}{% endif %}. If you don't want to use:

{% if form.title.errors %}error{% endif %}

You can try:

{{ error|default:'' }}

And the test in django template is bellow:

...from django.template import Context, Template
...from django.conf import settings
...settings.configure()
...t = Template("My name is: {{ name|default:'anonymous' }} ")

If default:

...t.render(Context({}))

it will return:

'My name is anonymous '

If has name:

...t.render(Context({"name": "John"}))

result:

'My name is John '

Read more: https://docs.djangoproject.com/en/1.9/ref/templates/

Upvotes: 2

2ps
2ps

Reputation: 15926

You can get more or less the behavior you want by using the yesno filter (documentation):

{{ form.title.errors|yesno:"errors," }}

Upvotes: 3

Related Questions