I\'m generating a dynamic form using wtforms (and flask). I\'d like to add some custom css classes to the fields I\'m generating, but so far I\'ve been unable to do so. Usin
Pretty late though, but here is what I found. While rendering a template you can pass any key-value pairs inside the parenthesis, and it just puts those key values while rendering. For example, if you had to put a class along with some placeholder text you can do it like below:
{{ form.email(class='custom-class' placeholder='email here') }}
will actually render like below:
Basically, you can even try experimenting by adding some non-existent HTML attribute with some value and it gets rendered.
To make it a less of pain its good to have helper functions as macros and render them instead of actual fields directly. Let's say you have common classes and error-classes. You can have a helper macro like this:
{% macro render_field(field,cls,errcls) %}
{% if field.errors %}
{{ field(class = cls + " " + errcls,**kwargs) | safe}}
{% for error in field.errors %}
{{error}}
{% endfor %}
{% else %}
{{ field(class = cls,**kwargs) | safe}}
{% endif %}
{% endmacro %}
Now while rendering a field you can call like this with additional attributes like this in the template:
{{render_field(form.email,cls="formcontrol",errcls="isinvalid",placeholder="Your Email") }}
Here I have used bootstrap classes, just modify the helper function to your needs!
Hope that helps! Happy coding!