问题描述
@app.route('/view', methods=['GET', 'POST'])
def view_notifications():
posts = get_notifications()
return render_template("frontend/src/view_notifications.html", posts=posts)
所以在我的 project / backend / src / app.py
中有此代码。我如何使用尝试引用
但它一直在说找不到该路径。我应该采取另一种方式吗? project / frontend / src / view_notifications.html
中的模板。
So in my project/backend/src/app.py
there's this code. How would I reference the template that's in project/frontend/src/view_notifications.html
I've tried using ..
but it keeps saying the path isn't found. Is there another way I should be doing this?
[Tue Jun 23 12:56:02.597207 2015] [wsgi:error] [pid 2736:tid 140166294406912] [remote 10.0.2.2:248] TemplateNotFound: frontend/src/view_notifications.html
[Tue Jun 23 12:56:05.508462 2015] [mpm_event:notice] [pid 2734:tid 140166614526016] AH00491: caught SIGTERM, shutting down
推荐答案
烧瓶正在寻找在 templates / frontend / src / view_notifications.html
中找到您的模板文件。您要么需要将模板文件移动到该位置,要么更改默认模板文件夹。
Flask is looking in templates/frontend/src/view_notifications.html
for your template file. You either need to move your templates file to that location or change the default template folder.
根据Flask文档,您可以为模板指定其他文件夹。在应用程序的根目录中,默认值为 templates /
:
According to the Flask docs you can specify a different folder for your templates. It defaults to templates/
in the root of your app:
import os
from flask import Flask
template_dir = os.path.abspath('../../frontend/src')
app = Flask(__name__, template_folder=template_dir)
更新:
经过测试我自己在Windows机器上,templates文件夹确实需要命名为 templates
。这是我使用的代码:
After testing it myself on a Windows machine the templates folder does need to be named templates
. This is the code I used:
import os
from flask import Flask, render_template
template_dir = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
template_dir = os.path.join(template_dir, 'frontend')
template_dir = os.path.join(template_dir, 'templates')
# hard coded absolute path for testing purposes
working = 'C:\Python34\pro\\frontend\\templates'
print(working == template_dir)
app = Flask(__name__, template_folder=template_dir)
@app.route("/")
def hello():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
具有以下结构:
|-pro
|- backend
|- app.py
|- frontend
|- templates
|- index.html
更改'templates'
的任何实例到'src'
并将template文件夹重命名为 src
会导致收到相同的错误OP。
Changing any instance of 'templates'
to 'src'
and renaming the templates folder to 'src'
resulted in the same error OP received.
这篇关于如何从python flask中的其他目录引用HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!