首页 > 解决方案 > Jinja2 将 WTF-Form 获取/导入到 Basic.html(包含在其他每个 html 页面中)

问题描述

我用 WTF-Forms 创建了一个表单:

class ContactForm(FlaskForm):
    report = TextAreaField('Nachricht', validators=[DataRequired(message="Geben Sie Ihre Nachricht ein")])
    contact_email = TextField('Ihre Email')

我的烧瓶应用程序的每个页面上都需要此表单,它位于页脚中。

服务器使用以下内容创建 html 页面render_template

# Index
@app.route('/', methods=["GET","POST"])
def index():   
    form_contact_us = ContactForm(prefix="contact-us-form") 
    return render_template('index.html', form_contact_us=form_contact_us)

我通常给出所有表格,我习惯于render_template. 但是如果我这样做,我将需要在每个函数上实现它,这会将 HTML 提供给客户端。我可以这样做,但我觉得应该有更好更快的解决方案。我自己无法找到解决方案,也许有人知道。

PS:

我有一个basic.html被其他所有 html 页面使用的。我在basic.html

标签: pythonflaskjinja2wtforms

解决方案


最简单的解决方案是使用context_processor. 这可确保contact_form表单变量存在于所有模板中。

@app.context_processor
def inject_contact_form():
    return dict(contact_form=ContactForm(prefix="contact-us-form"))

然后,您basic.html可以像往常一样呈现表单:

{{ contact_form.report.label }}<br>
{{ contact_form.report(size=32) }}

推荐阅读