2
votes

I am using Flask, WTForms and Backbone.js to create my app. I am working with Backbonejs for first time.

I have created a Backbone js template to display data and its corresponding form.

    <%= my_field1 %>
    <%= my_field2 %>
    <form>
        <input type="text" value="<%= my_field1 %>"/>
        <input type="text" value="<%= my_field2 %>"/>
    </form>

I am using WTForms and Jinja2 to render my form. To give initial value I am doing this

    {{ field1(value="<%= my_field1 %>") | safe }}
    {{ field1(value="<%= my_field1 %>") | safe }}

This is a source of problem as <% is escaped while rendering. How can I stop wtforms/jinja from escaping this?

1

1 Answers

1
votes

I looked at WTForms' source code, and yeah, it escapes HTML characters as part of rendering, which you're doing by calling the field. So the jinja "safe" parameter is acting too late.

You can get around this by creating a custom widget to render your field:

http://wtforms.simplecodes.com/docs/0.6/widgets.html#custom-widgets

I took a crack at writing a widget for you - I apologize that I haven't run this code, but it should be enough to get you going in the right direction.

If you run into trouble, be sure to check out WTForms' source code: it's well-commented, there's not a lot of it, and you can crib from there. (I did!)

from wtforms.widgets.core import HTMLString 

# Custom widget display 
def input_field_with_unescaped_value(field, **kwargs):

  value = kwargs.pop('value', field._value())
  unescaped_output = u' value="%s"' % value if value else ''

  return HTMLString(u'<input %s%s>%s</input>' % \
      (html_params(name=field.name, **kwargs), \
      unescaped_output, \
      unicode(field._value()))

# and here's how you use it in a form
class MyForm(Form):
  field1 = TextField(u'Thingy', widget=input_field_with_unescaped_value)