问题
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?
回答1:
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"})
回答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')
回答3:
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/
来源:https://stackoverflow.com/questions/27779024/setting-data-attributes-on-a-wtforms-field