我制作了一个烧瓶脚本,该脚本运行良好,但是我试图在另一个html页面上的表中显示某些值,由于某种原因,该值没有发生。
我已经尝试过jinja2文档和其他一些答案,但是并没有太大帮助。
flask file.py
from flask import Flask,render_template,request
app = Flask(__name__)
from webscraper import keeda,display_tbl
@app.route('/', methods=['POST', 'GET'])
def scraper():
if request.method == 'POST':
url = request.form['url']
df=keeda(url)
return render_template(('completed.html',display_tbl(df)))
else:
return render_template('index.html')
if __name__ == '__main__':
app.run()
the completed.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ display_tbl(df) }}
</div>
</body>
</html>
here's the error: jinja2.exceptions.UndefinedError: 'display_tbl' is undefined
i wanted to display a table with values on this page.
您期望jinja2可以为您做更多。请理解jinja2只是一种渲染模板的方法,这些模板最终是html和javascript,没有什么花哨的地方。因此,在您的情况下,您无法将Python函数传递给jinja2模板,并且无法正常运行。您可以在这里做的是在渲染模板时传递display_tbl
返回的数据:
def scraper():
...
return render_template(('completed.html', data=display_tbl(df))) # data= is important because this is how you are going to access your data in the template
…
def display_tbl(df):
… # Here you should be returning the data you want to display - a list or dict
在模板中
<html>
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ render_data() }}
</div>
<script>
var d = data | tojson
function render_data() {
// implement the logic to handle how your data should be rendered
}
</script>
</body>
</html>
这只是一个粗略的主意,但是正如您所看到的,您需要更改感知jinja2模板及其与Python或Flask后端交互的方式。