python - Flask Blueprint 扩展布局但找不到模板
问题描述
我有以下代码结构:
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 下的 templates 文件夹中搜索,所以我不太明白为什么它找不到这个 template layout.html
。
解决方案
该问题与模板目录的位置有关。这应该在根项目下,而不是在 app 文件夹下。
app/
home/
__init__.py
routes.py
templates/
home
index.html
todo/
__init__.py
routes.py
templates/
todo/
list.html
update.html
__init__.py
config.py
models.py
static
templates/
layout.html
在这种情况下,Flask 会找到 layout.html 模板。
推荐阅读
- node.js - 将投票应用程序的投票保存在 Mongo 数据库中
- r - 绘制每个日期的项目发生情况
- java - NoClassDefFoundError:无法初始化类 sun.awt.X11FontManager
- python - 我将如何根据发送的命令的输出打印一条读取“检测到输入错误”的行?
- python-3.x - 如何暂停在 Sublime 中运行的代码?
- android - Cordova Instascan - 无法访问视频流
- java - 具有非 void 返回值的 @EventListener 注释方法不会触发新事件
- symfony - 如何放置外部链接+参数
- javascript - Google Calendar API - 推送通知不起作用
- javascript - ActionController::ParameterMissing(参数丢失或值为空:JSON simple_form_for