[FIXED] How to incorporate multiple CSS classes into a Flask WTForms?

Issue

I’m using Flask WTForms to generate some Bootstrap 5 forms. They looks a bit like this:

class NetworkForm(FlaskForm):
    name = StringField('Network Name', validators=[DataRequired()])
    sector = SelectField('Sector', choices=[], validators=[DataRequired()])

I populate the sectors dynamically but want to add a couple of classes to the fields so followed this question/answer which said to add them into the Jinja template as a class_ which worked with a single CSS class like this:

{{ form.name.label(class_="form-label") }}
{{ form.name(class_="form-control") }}

The issues I have is when I need to add multiple classes.

{{ form.name.label(class_=["form-label", "my-other-class"]) }}
{{ form.name(class_=["form-control", "my-other-class"]) }}

But that doesn’t appear to work. Is there any way to add multiple CSS classes?

Solution

Concatenate the class names into a string, just like you would inside the html attribute.

{{ form.name.label(class_="form-label my-other-class") }}
{{ form.name(class_="form-control my-other-class") }}

Answered By – Detlef

Answer Checked By – Cary Denson (FixeMe Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *