Setting data attributes on a WTForms field
Asked Answered
U

4

14

I want to add "data-" attributes to a form field for integration with Bootstrap. I tried the following in a template:

{{ form.test(data-toggle="toggle", data-size="mini", data-on="Yes", data-off="No", type="checkbox")}}

and got this error:

TemplateSyntaxError: expected token ',', got '='

Why did I get this error and how do I fix it?

Ubiety answered 5/1, 2015 at 11:56 Comment(0)
R
20

You need to use valid Python names as the variable names. Therefore names like "data-toggle" are invalid because they have a "-" in them. Change the names to use underscores, like "data_toggle". WTForms automatically converts "_" to "-" for keywords it doesn't recognize.

{{ form.test(data_size="mini") }}

You can also use dict unpacking to pass keyword arguments with keys that aren't valid variables.

{{ form.name(**{"data-size": "mini"}) }}

Rather than setting the attributes when rendering, you can set the default attributes for the field with render_kw.

class ExampleForm(Form):
    name = StringField(render_kw={"data-size": "mini"})
Rodomontade answered 5/1, 2015 at 12:19 Comment(0)
P
2

When creating a form add any data-* fields as a render_kw dictionary in the field definition. As follows in this example using Knockout:

class ScheduledReportForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()], render_kw={'data-bind':'value: name'})

    submit = SubmitField('Submit')
Polio answered 6/7, 2018 at 0:59 Comment(0)
H
2

As davidism explained, names like "data-toggle" aren't valid.

However, davidism's solution didn't work for me, WTFForm didn't convert '_' to '-'.

Maybe my version of WTFForms is too old (Flask-WTF==0.8.2 WTForms==1.0.2).

Alternatively, you can pass the HTML attributes that contain invalid syntax as an ad-hoc dictionary.

{{ form.test(type="checkbox", **{'data-toggle':'toggle', 'data-size'='mini', data-on="Yes"} )}}

Reference: http://flask.pocoo.org/snippets/107/

Humph answered 9/8, 2018 at 5:4 Comment(0)
U
1

If you want to add an attribute like "disabled" or "readonly" then you can do it like this

{{ form.test(class_="input", readonly="readonly") }}
Untoward answered 1/3, 2022 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.