Ternary condition in Django Templates

Asked

Viewed 90 times

0

I wish I could do that:

{% if is_premium > 0 %}
    <span class="text-success d-block">Você é Premium e possui {{ is_premium }} {{ ' dias' if is_premium > 1 else ' dia' }}</span>
{% else %}
    <span class="text-danger d-block">Você não é Premium</span>
{% endif %}

Thereby:

{% if is_premium > 0 %}
    {% if is_premium > 1 %}
        <span class="text-success d-block">Você é Premium e possui {{ is_premium }} dias</span>
    {% else %}
        <span class="text-success d-block">Você é Premium e possui {{ is_premium }} dia</span>
    {% endif %}
{% else %}
    <span class="text-danger d-block">Você não é Premium</span>
{% endif %}

Only Django doesn’t accept this kind of condition:

{{ ' dias' if is_premium > 1 else ' dia' }}

Django has some similar functionality in the templates system?

I’ll be honest, I’ve focused so much on models I ended up reading little the documentation that talks about templates.

1 answer

2


Live you can see more details here, that is, there are several ways to use the Ernary condition:

{% firstof var1 var2 var3 %}

Or

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

In the link above you have more examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.