1

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"))
BluebayX
  • 15
  • 3
  • What are you trying to achieve? Since the HTML response is just a string, what would providing context variables do? – MatsLindh Jun 08 '22 at 13:27
  • I want to insert a variable from my FastAPI backend app to a vue.js frontend app. The vue.js app has one .html file full of js with nearly no html in it. So I want to insert my variable to the src/views/home/Contents.vue file. – BluebayX Jun 08 '22 at 14:52
  • Inserting dynamic content into HTML is what `TemplateResponse` is for. BUT; generally (and your use case might be different, since you haven't given any information in your question) this is not how you transfer data to your Vue app, since the Vue app (including the index.html file) will be built from the source and deployed separately from FastAPI - instead, Vue would retrieve the necessary data from an endpoint when starting up, delivering _the same_ app to every user (which makes the built Vue app completely static and cachable). – MatsLindh Jun 08 '22 at 19:17

1 Answers1

0

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/

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62