Search code examples
python-3.xfastapistarlette

How to add context to HTMLResponse?


How to add context to HTMLResponse as you can do with TemplateResponse to insert content into the HTML site? Example with TemplateResponse:

return templates.TemplateResponse('index.html', context={'request': request, "Variable1": V1, "Variable2": V2})

And how to add the context here?:

@app.get("/")
def root():
    return HTMLResponse(pkg_resources.resource_string(__name__, "index.html"))

Solution

  • You can use jinja to achieve solution to your problem.

    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    
    app = FastAPI()
    
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    
    templates = Jinja2Templates(directory="templates")
    
    
    @app.get("/items/{id}", response_class=HTMLResponse)
    async def read_item(request: Request, id: str):
        context = {'request': request, "Variable1": V1, "Variable2": V2}
        return templates.TemplateResponse("item.html", context)
    

    Reference: https://fastapi.tiangolo.com/advanced/templates/