How check empty variable in template? Exception Value: Could not parse the remainder

Issue

{% extends 'pygiustizia/base.html' %}
{% block body %}
<div class="wrapper">
    <h2>Login</h2>
    <p>Prego, inserisci le tue credenziali di login.</p>

    <div class={% if len(tmplVar.loginErr) > 0  %} "alert alert-danger" {% endifequal %}> {% if tmplVar.loginErr is not None %} {{tmplVar.loginErr}} {% endif %}</div>
    <form action="{% url 'login' %}" method="post">
        <div class="form-group">
            <label>Username</label>
            <input type="text" name="username" class="form-control {% if tmplVar.usernameErr is not None %} is-invalid {% endif %}" value="{{tmplVar.username}}">
            <span class="invalid-feedback">{% if tmplVar.usernameErr is not None %} {{tmplVar.usernameErr}} {% endif %}</span>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" class="form-control {% if tmplVar.passwordErr is not None %} is-invalid {% endif %}" value="{{tmplVar.password}}">
            <span class="invalid-feedback">{% if tmplVar.passwordErr is not None %} {{tmplVar.passwordErr}} {% endif %}</span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Login">
        </div>
    </form>
</div> 
{% endblock %}

Exception Value: Could not parse the remainder: ‘(tmplVar.loginErr)’ from ‘len(tmplVar.loginErr)’

What I miss? How can I check if variable is empty or lenght 0?

Solution

You can not use len(…): function calls are deliberately restricted in Django’s template language. You can make use of the |length template filter [Django-doc]. But here checking the truthiness is enough:

<div {% if tmplVar.loginErr %}class="alert alert-danger"{% endif %}>

this will check if the length is greater than zero, since collections (lists, tuples, strings, etc.) have truthiness False if these are empty.

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published