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在循环中渲染所有输入字段,而不是为每个输入字段编写代码。但每个字段都会有不同的colspan
对应<td>
中的值。
如何为 colspan 添加可在 <td>
中使用的自定义参数?
类似:(只是上面代码中的 diff
)
forms.py
my_field = TextField(colspan="4")
my_form.html
<td colspan={{form.my_field.colspan}}>
最佳答案
您需要创建一个custom field带有额外的 colspan
属性。
首先定义自定义字段子类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}}">
关于python - Flask-WTFoms 字段中的自定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544715/