Jinja2 テンプレート
この章では、FastAPI で Jinja2 テンプレートエンジンを設定し、静的ファイルとテンプレート継承を使って完全な HTML ページを構築する方法を学びます。
FastAPI の 2 つのレンダリングモード
FastAPI はデフォルトで JSON を返します(API 向け)が、HTML を返すこともできます(SSR 向け)。
2 つのモードは共存できます。同じプロジェクトで JSON API を提供することも、Web ページをレンダリングすることもできます。
静的ファイルのマウント
静的ファイル(CSS、JS、画像)はStaticFiles指定されたパスにマウントされます。
実例
# ファイルパス: main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# static/ ディレクトリを /static パスにマウント
# /static/css/style.css にアクセス → 実際に static/css/style.css を読み取る
app.mount("/static", StaticFiles(directory="static"), name="static")
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# static/ ディレクトリを /static パスにマウント
# /static/css/style.css にアクセス → 実際に static/css/style.css を読み取る
app.mount("/static", StaticFiles(directory="static"), name="static")
テンプレートで静的ファイルを参照する:
実例
<link rel="stylesheet" href="/static/css/style.css">
<img src="/static/images/logo.png">
<img src="/static/images/logo.png">
Jinja2 テンプレートの設定
実例
# ファイルパス: main.py
from fastapi import FastAPI, Request
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("/")
def index(request: Request): # 注意: テンプレートルートは Request パラメータを受け取る必要があります
"""ブログホームページ"""
return templates.TemplateResponse(
"index.html", # テンプレートファイル名
{ # context データ
"request": request, # request を必ず渡す(Jinja2Templates の要件)
"title": "サンプル ブログ"
}
)
from fastapi import FastAPI, Request
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("/")
def index(request: Request): # 注意: テンプレートルートは Request パラメータを受け取る必要があります
"""ブログホームページ"""
return templates.TemplateResponse(
"index.html", # テンプレートファイル名
{ # context データ
"request": request, # request を必ず渡す(Jinja2Templates の要件)
"title": "サンプル ブログ"
}
)
FastAPI のテンプレートレンダリングには Flask と 2 つの重要な違いがあります:1. ビュー関数は必ず受け取る必要があります
request: Requestパラメータ;2.request必ず context としてテンプレートに渡す必要があります。request を渡し忘れると、テンプレート内の url_for 機能が動作しなくなります。
base.html 親テンプレートを作成
実例
<!-- ファイルパス: templates/base.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}サンプル ブログ{% endblock %}</title>
<link rel="stylesheet" href="/static/css/style.css">
{% block extra_head %}{% endblock %}
</head>
<body>
<header class="navbar">
<a href="/" class="logo">サンプル ブログ(FastAPI)</a>
<nav>
<a href="/">ホーム</a>
<a href="#">このサイトについて</a>
</nav>
</header>
<main class="container">
{% block content %}{% endblock %}
</main>
<footer class="footer">
<p>© 2024 サンプル ブログ. Powered by FastAPI.</p>
</footer>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}サンプル ブログ{% endblock %}</title>
<link rel="stylesheet" href="/static/css/style.css">
{% block extra_head %}{% endblock %}
</head>
<body>
<header class="navbar">
<a href="/" class="logo">サンプル ブログ(FastAPI)</a>
<nav>
<a href="/">ホーム</a>
<a href="#">このサイトについて</a>
</nav>
</header>
<main class="container">
{% block content %}{% endblock %}
</main>
<footer class="footer">
<p>© 2024 サンプル ブログ. Powered by FastAPI.</p>
</footer>
</body>
</html>
index.html 子テンプレートを作成
実例
<!-- ファイルパス: templates/index.html -->
{% extends 'base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h2 class="section-title">最新記事</h2>
<p>記事一覧は後の章で表示されます。</p>
{% endblock %}
{% extends 'base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h2 class="section-title">最新記事</h2>
<p>記事一覧は後の章で表示されます。</p>
{% endblock %}
FastAPI テンプレート内の url_for()
Flask と同様に、FastAPI もサポートしていますurl_for()が、先にルートに名前を付ける必要があります。
実例
@app.get("/post/{post_id}", name="post_detail") # name= でルートに名前を付ける
def post_detail(request: Request, post_id: int):
return templates.TemplateResponse("post_detail.html",
{"request": request, ...})
def post_detail(request: Request, post_id: int):
return templates.TemplateResponse("post_detail.html",
{"request": request, ...})
実例
<!-- テンプレートで参照 -->
<a href="{{ url_for('post_detail', post_id=3) }}">記事 3</a>
<a href="{{ url_for('post_detail', post_id=3) }}">記事 3</a>
基本 CSS スタイルを作成
実例
/* ファイルパス: static/css/style.css */
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
color: #333;
}
.navbar {
display: flex; justify-content: space-between; align-items: center;
padding: 16px 40px; background: #fff;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.navbar .logo {
font-size: 22px; font-weight: bold;
color: #009688; text-decoration: none;
}
.navbar nav a {
margin-left: 20px; text-decoration: none; color: #333;
}
.container { max-width: 960px; margin: 40px auto; padding: 0 20px; }
.footer { text-align: center; padding: 20px; color: #999; border-top: 1px solid #eee; }
.section-title { font-size: 24px; margin-bottom: 20px; }
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
color: #333;
}
.navbar {
display: flex; justify-content: space-between; align-items: center;
padding: 16px 40px; background: #fff;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.navbar .logo {
font-size: 22px; font-weight: bold;
color: #009688; text-decoration: none;
}
.navbar nav a {
margin-left: 20px; text-decoration: none; color: #333;
}
.container { max-width: 960px; margin: 40px auto; padding: 0 20px; }
.footer { text-align: center; padding: 20px; color: #999; border-top: 1px solid #eee; }
.section-title { font-size: 24px; margin-bottom: 20px; }
本章のまとめ
この章では、FastAPI のフロントエンドレンダリング設定を学びました:StaticFiles での静的リソースのマウント、Jinja2Templates でのテンプレートディレクトリの設定、TemplateResponse での HTML の返却、Flask とのテンプレートレンダリングにおける重要な違い(Request パラメータを必ず渡すこと)です。
その他の拡張