Conditionally apply CSS class to wtforms element in Python flask

43 Views Asked by At

I want to apply an additional is-invalid CSS class to a wtforms element only if there is an error present in the form.

I've landed on the following code to achieve this and it works:

{% if form.email.errors %}
{{ form.email(placeholder="Email", class="form-control is-invalid") }}
{% else %}
{{ form.email(placeholder="Email", class="form-control") }}
{% endif %}

However, it's not very consise and i'm having to repease the whole form.email element. This could get real messy if the logic was more complicated.

There must be a cleaner way to have only the class value wrapped in logic.

2

There are 2 best solutions below

0
pjcunningham On

You could use the string concatenation operator "~" with an inline if statement, e.g.

{{ form.email(placeholder="Email", class="form-control" ~ " is-invalid" if form.email.errors else "") }}
0
Sobigen On

Try jinja macros. In your template you can put this and then modify the logic if you're looking to expand things.

{% macro render_email_field(field) %}
    {% if field.errors %}
        {{ field(placeholder="Email", class="form-control is-invalid") }}
    {% else %}
        {{ field(placeholder="Email", class="form-control") }}
    {% endif %}
{% endmacro %}

{{ render_email_field(form.email) }}

You can also put macros into a separate file and bring them into a particular template with

{% from "_jinja_macros.html" import render_email_field %}