如何区分jinja2中的字段和子表单?

时间:2019-09-26 16:25:20

标签: python-3.x jinja2 flask-wtforms

我使用Flask用表单编写了一个flask_wtf应用程序。我的表单包含字段和子表单。我的目标是使用循环渲染所有字段,并自行处理子表单。是否可以区分字段和子表单(在jinja2模板中使用if语句)?

form.py

from flask_wtf import form, FlaskForm
from wtforms import StringField, FieldList, FormField


class MySubform(Form):
    field1 = StringField(label="field1")


class MyForm(Flaskform):
    name = StringField(label="Name")
    subform = FieldList(FormField(MySubform), min_entries=1)

index.html

{% extends "bootstrap/base.html" %}

{% block content %}

<div class="row">
    {% for field in form %}
        <div class="form-group">
            {{ field.label(class_='col-sm-3 control-label') }}
            <div class="col-sm-9">
                {{ field(class_='form-control') }}
            </div>
        </div>        
    {% endfor %}        
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

index.html

{% for field in form %}
    {% if field.type == 'FieldList' %}
        // Process Subfields
    {% else %}
        // Process everything except FieldList's
    {% endif %}
{% endfor %}