How to add an attribute that contains a hyphen to a WTForms field
Asked Answered
D

2

12

Calling a WTForms field object produces the rendered field, and any arguments are taken as attributes, for instance.

form.field(attribute='value')

would return something like

<input attribute='value'>

How can I add HTML5 custom data attributes such as data-provide which contain hyphens, making them unparseable in python as a single keyword argument?

Damicke answered 5/9, 2012 at 15:22 Comment(0)
L
25

Create a dictionary with the corresponding key-value pairs and use ** to pass it to the field call:

attrs = {'data-provide': "foo"}
form.field(**attrs)

Edit: Looks like the comment by @NiklasB should be part of the answer: For those using flask with flask-WTF, use: {{ form.field( **{'data-provide': 'foo'} ) }} in your template.

Leatri answered 5/9, 2012 at 16:20 Comment(3)
For those using flask with flask-WTF, use: {{ form.field( **{'data-provide': 'foo'} ) }} in your templateMoonseed
Thanks for this -- awesome work. I did the following: {{ form.phone( **{'data-format': '(ddd) ddd-dddd', 'class':'form-control bfh-phone', 'placeholder':'Phone'} ) }}Bringhurst
Its works, but why is this working only when we create and unpack the dictionary and not working when we directly provide the parameters?Channa
A
-1

It's not necessary to use a dictionary like that in the form.field function call. The ** unpacks the dictionary items into named parameters for the function, so just add the parameters instead:

{{ form.field( data-provide='foo') }}

But do so AFTER any required parameters for that field. In other words, why unpack a dictionary right there when you can just add the parameters?

Ascription answered 6/12, 2017 at 9:39 Comment(1)
This doesn't work because the wtforms parameters are Python syntax, and a property with a hyphen is not valid Python syntax. Doing this raises a TemplateSyntaxError.Epistemic

© 2022 - 2024 — McMap. All rights reserved.