Flask-WTFoms 字段中的自定义参数

Custom parameter in Flask-WTFoms field

forms.py

my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])

my_form.html

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

这是一个简单的代码。但我想按照 this 的方式在循环中呈现所有输入字段,而不是为每个输入字段编写代码。但是每个字段在相应的 <td> 中都会有不同的 colspan 值。

如何为可以在 <td> 中使用的 colspan 添加自定义参数?

类似于:(只是上面代码中的 diff

forms.py

my_field = TextField(colspan="4")

my_form.html

<td colspan={{form.my_field.colspan}}>

您需要创建一个带有额外 colspan 属性的 custom field

首先定义自定义字段子类TextField:

class MyCustomTextField(TextField):
    def __init__(self, colspan=4, *args, **kwargs):
        super(MyCustomTextField, self).__init__(*args, **kwargs)
        self.colspan = colspan

现在在您的表单中使用自定义字段:

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

看到 MyCustomTextField 的第一个参数(本例中为 4)了吗?那是你的 colspan 属性。

最后,像这样访问模板中的属性:

<td colspan="{{form.my_field.colspan}}">