我是Flask的新手,並且正在使用搜索工具編寫一個簡單的Flask應用程序。與谷歌搜索類似,我希望在搜索結果頁面中保留搜索輸入框,同時顯示搜索結果。因此,我將搜索表單放在基本模板中,並從基本模板中放置派生搜索結果模板,以顯示搜索表單和搜索結果。燒瓶:我如何在基礎jinja2模板中放置窗體?
對於這一點,我做了以下內容: -
基本模板(base.html文件)與頁面的元數據和表格(這應該主要是目前甚至在結果頁面)。
<html>
<head>
{% if title %}
<title>{{title}}</title>
{% else %}
<title>Search</title>
{% endif %}
</head>
<body>
<h1>Search </h1>
<form action="/series_search" method="post" name="search">
{{form.hidden_tag()}}
<p>
Please enter query: <br>
{{form.search(size=10)}}
</p>
<p><input type="submit" value="Search"></p>
</form>
<br>
{% block content %}{% endblock %}
</body>
</html>
衍生的模板(derived.html)具有下面的代碼,其被inhering基本模板(其具有該檢索樣板):
{% extends "base.html" %}
{% block content %}
<h1>Search Result</h1>
{% if result %}
<p> Title: {{result.title}}</p>
{% else %}
<p> search not found!!</p>
{% endif %}
{% endblock %}
並且,在視圖中,以下
@app.route('/search', methods = ['POST', 'GET'])
def search():
form = SearchForm()
if form.validate_on_submit():
print "form validated"
query = form.search.data
result = Lib.get_result(query)
return render_template('derived.html', result = result)
return render_template('search.html',
title = 'Search',
form = form)
如果我輸入查詢並提交搜索表單,我得到以下錯誤,
....
....
File "/Users/webapp/app/templates/derived.html", line 1, in top-level template code
{% extends "search.html" %}
File "/Users/webapp/app/templates/search.html", line 12, in top-level template code
{{form.hidden_tag()}}
File "/Users/webapp/flask/lib/python2.7/site-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
所以,基本上按下提交按鈕後,視圖渲染派生自base.html的derived.html。 base.html有一個應該設置的表單。
- 如何在調用派生模板時傳遞基本模板的表單對象?
- 我的方法適合我想實現的目標嗎?如果有其他人,請提出建議。
請多關照
非常感謝。有效!!我不知道我是如何錯過它的。 –