Custom parameter in Flask-WTFoms field
<p><strong><em>forms.py</em></strong></p>

<pre><code>my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])
</code></pre>

<p><strong><em>my_form.html</em></strong></p>

<pre><code>&lt;table&gt;
  &lt;tr&gt;
    &lt;td colspan="4"&gt; 
      {{form.my_field(placeholder= form.my_field.label.text, class_="form-control")}}
      {% for error in form.my_field.errors %}
          &lt;span&gt;{{error}}&lt;/span&gt;
      {% endfor %}
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
</code></pre>

<p>This is a simple code. But I want to follow kind of <a href="http://stackoverflow.com/questions/16687520/jinja2-template-for-loop">this</a> to render all the input fields in a loop instead of writing the code for each of them. But each field will have a different <code>colspan</code> value in the corresponding <code>&lt;td&gt;</code>. </p>

<p>How can I add a custom parameter for colspan which I can use in the <code>&lt;td&gt;</code>?</p>

<p>Something like: (just the <code>diff</code> from above code)</p>

<p><strong><em>forms.py</em></strong></p>

<pre><code>my_field = TextField(colspan="4")
</code></pre>

<p><strong><em>my_form.html</em></strong></p>

<pre><code>&lt;td colspan={{form.my_field.colspan}}&gt;
</code></pre>

<p>You need to create a <a href="http://wtforms.simplecodes.com/docs/0.6.1/fields.html#custom-fields" rel="nofollow">custom field</a> with an extra <code>colspan</code> attribute.</p>

<p>First define the custom field sub classing <code>TextField</code>:</p>

<pre><code>class MyCustomTextField(TextField):
    def __init__(self, colspan=4, *args, **kwargs):
        super(MyCustomTextField, self).__init__(*args, **kwargs)
        self.colspan = colspan
</code></pre>

<p>Now use the custom field in your form:</p>

<pre><code>class MyForm(Form):
    my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])
</code></pre>

<p>See that first parameter (a <code>4</code> in this case) for <code>MyCustomTextField</code>? That's your colspan attribute.</p>

<p>Finally, access the attribute in your template like so:</p>

<pre><code>&lt;td colspan="{{form.my_field.colspan}}"&gt;
</code></pre>

python flask jinja2 flask-wtforms