Skip to content

📄

👆 💪 ⚙️ 🙆 📄 🚒 👆 💚 ⏮️ FastAPI.

⚠ ⚒ Jinja2️⃣, 🎏 1️⃣ ⚙️ 🏺 & 🎏 🧰.

📤 🚙 🔗 ⚫️ 💪 👈 👆 💪 ⚙️ 🔗 👆 FastAPI 🈸 (🚚 💃).

❎ 🔗

jinja2:

$ pip install jinja2

---> 100%

⚙️ Jinja2Templates

  • 🗄 Jinja2Templates.
  • templates 🎚 👈 👆 💪 🏤-⚙️ ⏪.
  • 📣 Request 🔢 ➡ 🛠️ 👈 🔜 📨 📄.
  • ⚙️ templates 👆 ✍ ✍ & 📨 TemplateResponse, 🚶‍♀️ request 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑".
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):
    return templates.TemplateResponse(
        request=request, name="item.html", context={"id": id}
    )

Note

👀 👈 👆 ✔️ 🚶‍♀️ request 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 ➡ 🛠️.

Tip

📣 response_class=HTMLResponse 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸.

📡 ℹ

👆 💪 ⚙️ from starlette.templating import Jinja2Templates.

FastAPI 🚚 🎏 starlette.templating fastapi.templating 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ Request & StaticFiles.

✍ 📄

⤴️ 👆 💪 ✍ 📄 templates/item.html ⏮️:

<html>
<head>
    <title>Item Details</title>
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
    <h1><a href="{{ url_for('read_item', id=id) }}">Item ID: {{ id }}</a></h1>
</body>
</html>

⚫️ 🔜 🎦 id ✊ ⚪️➡️ "🔑" dict 👆 🚶‍♀️:

{"request": request, "id": id}

📄 & 🎻 📁

& 👆 💪 ⚙️ url_for() 🔘 📄, & ⚙️ ⚫️, 🖼, ⏮️ StaticFiles 👆 📌.

<html>
<head>
    <title>Item Details</title>
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
    <h1><a href="{{ url_for('read_item', id=id) }}">Item ID: {{ id }}</a></h1>
</body>
</html>

👉 🖼, ⚫️ 🔜 🔗 🎚 📁 static/styles.css ⏮️:

h1 {
    color: green;
}

& ↩️ 👆 ⚙️ StaticFiles, 👈 🎚 📁 🔜 🍦 🔁 👆 FastAPI 🈸 📛 /static/styles.css.

🌅 ℹ

🌅 ℹ, 🔌 ❔ 💯 📄, ✅ 💃 🩺 🔛 📄.