Srd*_*tic 64 python templates file flask
我正在尝试渲染文件home.html.该文件存在于我的项目中,但是jinja2.exceptions.TemplateNotFound: home.html当我尝试渲染它时,我会继续这样做.为什么Flask找不到我的模板?
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
Run Code Online (Sandbox Code Playgroud)
/myproject
app.py
home.html
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 150
您必须在正确的位置创建模板文件; 在templatespython模块旁边的子目录中.
该错误表示目录中没有home.html文件templates/.确保您在与python模块相同的目录中创建了该目录,并且实际上您确实将该home.html文件放在该子目录中.如果您的应用是包,则应在包内创建模板文件夹.
myproject/
app.py
templates/
home.html
Run Code Online (Sandbox Code Playgroud)
myproject/
mypackage/
__init__.py
templates/
home.html
Run Code Online (Sandbox Code Playgroud)
或者,如果您将模板文件夹命名为除了templates并且不想将其重命名为默认文件夹之外的其他内容,则可以告诉Flask使用该其他目录.
app = Flask(__name__, template_folder='template') # still relative to module
Run Code Online (Sandbox Code Playgroud)
Non*_*one 15
(请注意,上面为文件/项目结构提供的公认答案是绝对正确的。)
还..
除了正确设置项目文件结构之外,我们还必须告诉 flask 在目录层次结构的适当级别中查找。
例如..
app = Flask(__name__, template_folder='../templates')
Run Code Online (Sandbox Code Playgroud)
app = Flask(__name__, template_folder='../templates', static_folder='../static')
Run Code Online (Sandbox Code Playgroud)
从开始../向后移动一个目录并从那里开始。
从开始../../向后移动两个目录并从那里开始(依此类推......)。
希望这可以帮助
我认为Flask默认使用目录模板。因此,您的代码应该假设这是您的hello.py
from flask import Flask,render_template
app=Flask(__name__,template_folder='template')
@app.route("/")
def home():
return render_template('home.html')
@app.route("/about/")
def about():
return render_template('about.html')
if __name__=="__main__":
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
你的工作空间结构就像
project/
hello.py
template/
home.html
about.html
static/
js/
main.js
css/
main.css
Run Code Online (Sandbox Code Playgroud)
您还创建了两个HTML文件,名称分别为home.html和about.html,并将它们放在模板文件夹中。
I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.
project/
app/
hello.py
static/
main.css
templates/
home.html
venv/
Run Code Online (Sandbox Code Playgroud)
This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.