Flask-WTFoms字段中的自定义参数 [英] Custom parameter in Flask-WTFoms field
问题描述
forms.py
forms.py
my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])
my_form.html
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
值.
This is a simple code. But I want to follow kind of this 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 colspan
value in the corresponding <td>
.
如何为可在<td>
中使用的colspan添加自定义参数?
How can I add a custom parameter for colspan which I can use in the <td>
?
类似的东西:(只是上面代码中的diff
)
Something like: (just the diff
from above code)
forms.py
forms.py
my_field = TextField(colspan="4")
my_form.html
my_form.html
<td colspan={{form.my_field.colspan}}>
推荐答案
You need to create a custom field with an extra colspan
attribute.
首先定义自定义字段子类TextField
:
First define the custom field sub classing TextField
:
class MyCustomTextField(TextField):
def __init__(self, colspan=4, *args, **kwargs):
super(MyCustomTextField, self).__init__(*args, **kwargs)
self.colspan = colspan
现在使用表单中的自定义字段:
Now use the custom field in your form:
class MyForm(Form):
my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])
看到MyCustomTextField
的第一个参数(在这种情况下为a 4
)吗?那就是你的colspan属性.
See that first parameter (a 4
in this case) for MyCustomTextField
? That's your colspan attribute.
最后,像这样访问模板中的属性:
Finally, access the attribute in your template like so:
<td colspan="{{form.my_field.colspan}}">
这篇关于Flask-WTFoms字段中的自定义参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!