Search code examples
pythonjinja2fastapi

jinja2.exceptions.TemplateNotFound: index.html FastAPI


I tried to use fastapi for rendering html files. I don't know why app can't find the template.

from starlette.templating import Jinja2Templates

from fastapi import FastAPI, Request, Response
from fastapi.responses import HTMLResponse


app = FastAPI()


templates = Jinja2Templates("templates")

@app.get("/", response_class=HTMLResponse)
def root(request: Request):
    return templates.TemplateResponse('index.html', context={'request': request})

enter image description here


Solution

  • that's not the root directory use this:

    templates = Jinja2Templates("app/templates")
    

    instead of this:

    templates = Jinja2Templates("templates")