python - 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
解决方案
最简单的解决方案是使用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) }}
推荐阅读
- jquery - 使用 jquery-datatables 获取数据
- unix - Kubernetes pod 将进入 crashloop 退避:在启动容器时说权限被拒绝
- node.js - 使用 Nodejs 实时抓取聊天记录
- javascript - Bootstrap 单选按钮“是”或“否”不接收更改或单击事件
- c# - UWP 应用程序上的文本框底部边框不可见
- php - 通过用户 id 从另一个表视图中获取用户名
- java - 向 Java 程序添加帐户登录 + HWID 锁的最安全方法是什么?
- constructor - 如何在 Flutter 中更改 Slider 标签颜色?
- c++ - 为什么我的重载强制转换运算符无法访问私有成员?
- c# - 尝试将 AutoMapper 与列表一起使用会返回错误“索引超出范围”。