Add a css class to a field in wtform

You actually don’t need to go to the widget level to attach an HTML class attribute to the rendering of the field. You can simply specify it using the class_ parameter in the jinja template.

e.g.

    {{ form.email(class_="form-control") }}

will result in the following HTML::

    <input class="form-control" id="email" name="email" type="text" value="">

to do this dynamically, say, using the name of the form as the value of the HTML class attribute, you can do the following:

Jinja:

    {{ form.email(class_="form-style-"+form.email.name) }}

Output:

    <input class="form-style-email" id="email" name="email" type="text" value="">

For more information about injecting HTML attributes, check out the official documentation.

Leave a Comment