为了使我的问题更清楚,这里有一个小应用程序,它输入一个句子并输出该句子两次。
我有base.html
:
<html>
<head>
<title> My site </title>
<body>
{% block content %}{% endblock %}
</body>
</html>
和index.html
:
{% extends "base.html" %}
{% block content %}
{{ s }}
<form action="" method="post" name="blah">
{{ form.hidden_tag() }}
{{ form.sentence(size=80) }}
<input type="submit" value="Doubler"></p>
</form>
{% endblock %}
以下是views.py
的一部分:
from forms import DoublerForm
@app.route('/index')
def index():
form = DoublerForm()
if form.validate_on_submit():
s = form.sentence.data
return render_template('index.html', form=form, s=str(s) + str(s))
return render_template('index.html', form=form, s="")
这里是forms.py
,没有所有导入:
class DoublerForm(Form):
sentence = StringField(u'Text')
这似乎工作正常。但我想要的是将我的输入表单放在base.html
模板中,以便显示在扩展它的所有页面上,而不仅仅是index
页面。如何将表单移动到base.html并为扩展base.html的所有视图实例化表单?
答案 0 :(得分:3)
You can use the flask.g object and flask.before_request
.
from flask import Flask, render_template, g
from flask_wtf import Form
from wtforms import StringField
@app.before_request
def get_default_context():
"""
helper function that returns a default context used by render_template
"""
g.doubler_form = DoublerForm()
g.example_string = "example =D"
@app.route('/', methods=["GET", "POST"])
def index():
form = g.get("doubler_form")
if form.validate_on_submit():
s = form.sentence.data
return render_template('index.html', form=form, s=str(s) + str(s))
return render_template('index.html', form=form, s="")
您还可以明确定义上下文功能
def get_default_context():
"""
helper function that returns a default context used by render_template
"""
context = {}
context["doubler_form"] = form = DoublerForm()
context["example_string"] = "example =D"
return context
并像这样使用
@app.route('/faq/', methods=['GET'])
def faq_page():
"""
returns a static page that answers the most common questions found in limbo
"""
context = controllers.get_default_context()
return render_template('faq.html', **context)
现在,您将拥有添加到解压上下文字典的所有模板中可用的上下文字典中的任何对象。
的index.html
{% extends "base.html" %}
{% block content %}
{{ s }}
{% endblock %}
base.html文件
<html>
<head>
<title> My site </title>
<body>
{% block content %}{% endblock %}
<form action="" method="post" name="blah">
{{ doubler_form.hidden_tag() }}
{{ doubler_form.sentence(size=80) }}
{{ example_string }}
<input type="submit" value="Doubler"></p>
</form>
</body>
</html>