in flask, framework, javascript, python, web

Combining jQuery Mobile and Flask-WTF may give you headaches, or why dashes suck in Python variable names

I thought developing using Flask on the backend and using jQuery on the front-end (navigator) would be quite easy. In fact it is, but there are some small traps that can take you time to resolve.

A regular case would be, when developing a form, to use Flask with WTForms (Flask-WTF to the rescue!). No problem, you end up with some Jinja2 templates like the following:

<form action="{{url_for('setup')}}" method="POST">
 {{form.channel}}
[...]

Here, you’re converting the variable “channel” which comes from a class defined in the Python Flask code, and thanks to WTForms will convert it to an HTML Select Box. You can also add arguments to that, which will be converted automatically to a pair key/value, for example, you can set {{form.channel(class=’foobar’)}}, which will translate in HTML to:

<select class="foobar" name="channel" [...]

The problem begins when you want to use the themes from jQuery, which are named like “data-theme”. Notice that cool dash (‘-‘)! It prevents you from using the same syntax in Jinja2, as you can’t directly use dashes in variable names. Hopefully, Karol Kuczmarski gave me the answer in the WTForms related Google Group:

{{ form.channel(**{'data-theme': 'b'}) }}