【发布时间】:2021-04-05 01:24:43
【问题描述】:
我的代码结构如下:
app/
home/
__init__.py
routes.py
templates/
home
index.html
static
templates/
layout.html
todo/
__init__.py
routes.py
templates/
todo/
list.html
update.html
__init__.py
config.py
models.py
在__init__.py 文件中,我有以下内容:
from flask import Blueprint
todo = Blueprint('todo', __name__, template_folder='templates')
from app.todo import routes
routes.py 文件包含:
from flask import request, render_template, redirect
from app.todo import todo
from ..models import Task, db
@todo.route('/todos')
def home():
tasks = Task.query.order_by(Task.created_at).all()
return render_template("todo/list.html", tasks=tasks)
todo/templates/todo/list.html 文件包含以下代码:
{% extends "layout.html" %}
{% block content %}
....
layout.html 文件位于app/templates 文件夹中。
我的app/__init__.py 文件有以下内容:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app.config import app_config
db = SQLAlchemy()
def init_app(app_name, config_name):
app = Flask(app_name)
app.config.from_object(app_config[config_name])
db.init_app(app)
with app.app_context():
from .home.routes import home
from .todo.routes import todo
app.register_blueprint(home)
app.register_blueprint(todo)
return app
当我通过 http://localhost:5000/todos 访问应用程序时,我收到以下消息:
jinja2.exceptions.TemplateNotFound: layout.html
我知道 Flask 会首先在 app 下的模板文件夹中搜索,所以我不太明白为什么它找不到这个模板 layout.html。
【问题讨论】:
-
不,该帖子处理蓝图中的模板用法。那部分对我有用。当我显示一个不扩展其他布局的模板时,一切正常。特别是当我在模板中扩展布局文件时,它抱怨它没有找到布局文件(我正在扩展)。
-
看看接受的答案,尤其是选项flask.pocoo.org/docs/1.0/config/#EXPLAIN_TEMPLATE_LOADING 可能这说明了为什么它找不到layout.html
-
谢谢。看帖子比较详细。基于这些提示,我找到了结果。我将其添加为单独的答案。