From: Francesco Frassinelli Date: Mon, 3 Aug 2020 07:53:56 +0000 (+0200) Subject: 📝 Add HTML media type to template docs (#1690) X-Git-Tag: 0.60.2~34 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=769ee73240da5586380bf0ca3cc3f3d8c2a2858a;p=thirdparty%2Ffastapi%2Ffastapi.git 📝 Add HTML media type to template docs (#1690) Co-authored-by: Sebastián Ramírez --- diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 871f3163f0..59d2735cb7 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -39,13 +39,16 @@ $ pip install aiofiles * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, passing the `request` as one of the key-value pairs in the Jinja2 "context". -```Python hl_lines="3 10 14 15" +```Python hl_lines="4 11 15 16" {!../../../docs_src/templates/tutorial001.py!} ``` !!! note Notice that you have to pass the `request` as part of the key-value pairs in the context for Jinja2. So, you also have to declare it in your *path operation*. +!!! tip + By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. + !!! note "Technical Details" You could also use `from starlette.templating import Jinja2Templates`. diff --git a/docs_src/templates/tutorial001.py b/docs_src/templates/tutorial001.py index b818861db7..245e7110b1 100644 --- a/docs_src/templates/tutorial001.py +++ b/docs_src/templates/tutorial001.py @@ -1,4 +1,5 @@ from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates @@ -10,6 +11,6 @@ app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") -@app.get("/items/{id}") +@app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): return templates.TemplateResponse("item.html", {"request": request, "id": id})