烧瓶蓝图扩展布局但找不到模板

时间:2020-12-28 08:30:29

标签: python flask

我有以下代码结构:

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

1 个答案:

答案 0 :(得分:1)

该问题与模板目录的位置有关。这应该在根项目下,而不是在 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 模板。