Modern Frontend Integration: Jinja2, HTMX & WebSockets
Build dynamic web applications without heavy JavaScript frameworks. Master Jinja2 template inheritance, HTMX for interactivity, server-sent events, WebSocket basics, and the hypermedia-driven architecture approach.
Build dynamic web applications without heavy JavaScript frameworks. Master Jinja2 template inheritance, HTMX for interactivity, server-sent events, WebSocket basics, and the hypermedia-driven architecture approach. This hands-on tutorial focuses on practical implementation of modern frontend integration: jinja2, htmx & websockets concepts.
Modern Frontend Integration: Jinja2, HTMX & WebSockets
React and Vue are great, but they're overkill for most web apps. Modern hypermedia tools like HTMX let you build rich, interactive UIs with server-rendered HTML — no JavaScript framework required. This chapter covers the stack that's making a comeback at companies like Basecamp and GitHub.
Jinja2 Template Inheritance
Template inheritance lets you define a base layout and override blocks. This eliminates repeated HTML:
templates/
├── base.html ← Base layout: nav, footer, scripts
├── pages/
│ ├── home.html ← {% extends "base.html" %}
│ └── dashboard.html
└── components/
├── user_card.html ← Reusable partial
└── modal.html
HTMX — Interactivity Without JavaScript Frameworks
HTMX extends HTML with attributes that trigger AJAX requests and swap response content into the DOM. No React, no state management, no build step:
<!-- Load data on click -->
<button hx-get="/api/stats" hx-target="#stats-container">
Load Stats
</button>
<div id="stats-container"></div>
<!-- Submit form via AJAX -->
<form hx-post="/submit" hx-swap="outerHTML">
<input name="email" type="email" required>
<button type="submit">Subscribe</button>
</form>
<!-- Load on page load -->
<div hx-get="/notifications" hx-trigger="load, every 30s"></div>
<!-- Infinite scroll -->
<div hx-get="/posts?page=2" hx-trigger="revealed" hx-swap="afterend"></div>
WebSockets with FastAPI
For real-time features (chat, live notifications, collaborative editing), WebSockets provide persistent bidirectional connections:
from fastapi import WebSocket, WebSocketDisconnect
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/chat/{room}")
async def chat_endpoint(websocket: WebSocket, room: str):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"{room}: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
Server-Sent Events (SSE)
For one-way real-time updates (progress bars, log streaming, notifications), SSE is simpler than WebSockets:
from fastapi.responses import StreamingResponse
import asyncio
@app.get("/events/progress")
async def progress_stream():
async def event_generator():
for i in range(1, 11):
yield f"data: {{'progress': {i * 10}}}\\n\\n"
await asyncio.sleep(1)
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
}
)
Client-side (HTML):
<script>
const evtSource = new EventSource("/events/progress");
evtSource.onmessage = (event) => {
const data = JSON.parse(event.data);
document.getElementById("progress").style.width = data.progress + "%";
};
</script>
AI Mentor
Confused about "Jinja2 templates HTMX server-rendered HTML WebSockets Server-Sent Events hypermedia architecture"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 10What problem does HTMX solve?
Key Takeaways
✅ Template inheritance eliminates HTML duplication across pages.
✅ HTMX adds AJAX, form submission, and DOM swapping to plain HTML.
✅ WebSockets for real-time bidirectional communication.
✅ Server-Sent Events for simple one-way streaming (progress, notifications).
✅ Hypermedia architecture is making a comeback — simpler, faster, more maintainable.
Keep coding! 🚀