1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
게시판

11 / 14

글 상세 페이지

카드를 누르면 /posts/1로 가는데 404죠. 상세 페이지를 만들어요. 그 전에 헤더를 두 페이지가 같이 쓰게 정리할게요.

공통 뼈대 base.html

templates/base.html 탭에 index.html의 뼈대를 옮겨요. 페이지마다 다른 부분만 {% block content %} 자리로 비워 둬요.

templates/base.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <header>
    <a href="/">crack.log</a>
    <button id="theme">☾</button>
  </header>
  <main>
    {% block content %}{% endblock %}
  </main>
  <script src="/static/script.js"></script>
</body>
</html>

templates/index.html은 전체를 이걸로 교체해요. 카드 부분만 남고 짧아져요.

templates/index.html
{% extends "base.html" %}
{% block content %}
<h1>내 블로그</h1>
<div class="cards">
  {% for post in posts %}
  <article class="card">
    <a href="/posts/{{ post.id }}">
      <img class="thumb" src="/static/{{ post.image }}" alt="">
      <div class="body">
        <h2>{{ post.title }}</h2>
        <p>{{ post.summary }}</p>
        <span class="date">{{ post.date }}</span>
      </div>
    </a>
    <div class="foot">
      <span>by <b>{{ post.author }}</b></span>
      <span>♥ {{ post.likes }}</span>
    </div>
  </article>
  {% endfor %}
</div>
{% endblock %}

{% extends "base.html" %}는 "base.html을 쓰되 content 자리에 아래 내용을 넣어라". 실행해서 화면이 그대로인지 확인하세요.

상세 페이지

templates/post.html을 채워요.

templates/post.html
{% extends "base.html" %}
{% block content %}
<article class="post">
  <h1>{{ post.title }}</h1>
  <p class="meta">{{ post.author }}, {{ post.date }}</p>
  <img class="cover" src="/static/{{ post.image }}" alt="">
  <p class="content">{{ post.body }}</p>
  <a class="back" href="/">목록으로</a>
</article>
{% endblock %}

app.py 맨 아래에 주소를 추가해요. 맨 윗줄 import에 HTTPException도 넣고요.

app.py
from fastapi import FastAPI, HTTPException, Request
app.py
@app.get("/posts/{post_id}", response_class=HTMLResponse)
def post_detail(request: Request, post_id: int):
    for post in posts:
        if post["id"] == post_id:
            return templates.TemplateResponse(request, "post.html", {"post": post})
    raise HTTPException(status_code=404, detail="그런 글은 없어요")
  • "/posts/{post_id}" 중괄호 부분은 뭐가 와도 돼요. /posts/1, /posts/2 전부 이 함수로 와요. 그 값이 post_id로 들어와요.
  • post_id: int 숫자로 바꿔서 받아요. /posts/abc로 오면 FastAPI가 알아서 거절해요.
  • for문으로 id가 같은 글을 찾아서 post.html에 넘겨요.
  • 못 찾으면 HTTPException 404. 2단계의 "그런 거 없는데"예요.

static/style.css 맨 아래에 상세 페이지 모양을 추가해요.

static/style.css
.post { max-width: 720px; margin: 0 auto; }
.post h1 { font-size: 36px; margin-bottom: 8px; }
.post .meta { color: var(--muted); margin-bottom: 24px; }
.post .cover { width: 100%; border-radius: 8px; }
.post .content { font-size: 17px; line-height: 1.8; }
.post .back { color: var(--mint); text-decoration: none; }

실행하고 카드를 눌러 보세요. 주소칸에 /posts/99도 쳐 보세요.

이 단계 전체 코드
app.py
from fastapi import FastAPI, HTTPException, 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")

posts = [
    {
        "id": 1,
        "title": "FastAPI 첫 서버 띄우기",
        "summary": "uvicorn 한 줄이면 끝. 흰 화면에 Hello World가 뜨는 순간부터 시작.",
        "body": "터미널에 uvicorn app:app --reload 를 치면 서버가 뜬다. 브라우저에서 localhost:8000 을 열면 내가 return 한 글자가 그대로 보인다. 여기서부터 전부 시작이다.",
        "date": "2026년 10월 10일",
        "author": "sfadfe",
        "likes": 518,
        "image": "thumb1.svg",
    },
    {
        "id": 2,
        "title": "Jinja2로 HTML 분리하기",
        "summary": "app.py 안에 HTML을 문자열로 두면 금방 지저분해진다. templates 폴더로 꺼내자.",
        "body": "Jinja2Templates(directory='templates') 한 줄이면 HTML 파일을 따로 둘 수 있다. 중괄호 두 개 안에 파이썬 값을 넣으면 그 자리에 찍힌다. 파일이 나뉘니까 어디를 고칠지 바로 보인다.",
        "date": "2026년 10월 11일",
        "author": "aa_100",
        "likes": 523,
        "image": "thumb2.svg",
    },
    {
        "id": 3,
        "title": "fetch로 DELETE 보내기",
        "summary": "버튼 하나에 fetch 한 줄. 서버는 리스트에서 글을 빼고 200을 돌려준다.",
        "body": "주소창으로는 GET밖에 못 보낸다. DELETE 는 JS 의 fetch 로 보낸다. 서버 쪽은 @app.delete 로 받는다. 받으면 리스트에서 글을 빼고 ok 를 돌려준다.",
        "date": "2026년 10월 12일",
        "author": "nosmeri",
        "likes": 9,
        "image": "thumb3.svg",
    },
]


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse(request, "index.html", {"posts": posts})


@app.get("/posts/{post_id}", response_class=HTMLResponse)
def post_detail(request: Request, post_id: int):
    for post in posts:
        if post["id"] == post_id:
            return templates.TemplateResponse(request, "post.html", {"post": post})
    raise HTTPException(status_code=404, detail="그런 글은 없어요")
templates/base.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <header>
    <a href="/">crack.log</a>
    <button id="theme">☾</button>
  </header>
  <main>
    {% block content %}{% endblock %}
  </main>
  <script src="/static/script.js"></script>
</body>
</html>
templates/index.html
{% extends "base.html" %}
{% block content %}
<h1>내 블로그</h1>
<div class="cards">
  {% for post in posts %}
  <article class="card">
    <a href="/posts/{{ post.id }}">
      <img class="thumb" src="/static/{{ post.image }}" alt="">
      <div class="body">
        <h2>{{ post.title }}</h2>
        <p>{{ post.summary }}</p>
        <span class="date">{{ post.date }}</span>
      </div>
    </a>
    <div class="foot">
      <span>by <b>{{ post.author }}</b></span>
      <span>♥ {{ post.likes }}</span>
    </div>
  </article>
  {% endfor %}
</div>
{% endblock %}
templates/post.html
{% extends "base.html" %}
{% block content %}
<article class="post">
  <h1>{{ post.title }}</h1>
  <p class="meta">{{ post.author }}, {{ post.date }}</p>
  <img class="cover" src="/static/{{ post.image }}" alt="">
  <p class="content">{{ post.body }}</p>
  <a class="back" href="/">목록으로</a>
</article>
{% endblock %}
static/style.css
:root {
  --bg: #f8f9fa;
  --panel: #ffffff;
  --text: #212529;
  --muted: #868e96;
  --line: #e9ecef;
  --mint: #12b886;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  font-family: -apple-system, "Segoe UI", "Noto Sans KR", "Malgun Gothic", sans-serif;
  background: var(--bg);
  color: var(--text);
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: var(--panel);
  border-bottom: 1px solid var(--line);
}

header a {
  font-size: 22px;
  font-weight: 800;
  color: var(--mint);
  text-decoration: none;
}

main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 32px;
}

h1 { font-size: 22px; }

.card {
  background: var(--panel);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.card a { color: inherit; text-decoration: none; }
.card .thumb { display: block; width: 100%; height: 160px; object-fit: cover; }
.card .body { padding: 16px; }
.card h2 { margin: 0 0 8px; font-size: 16px; }
.card p { margin: 0 0 12px; font-size: 14px; line-height: 1.5; color: var(--muted); }
.card .date { font-size: 12px; color: var(--muted); }

.card .foot {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  border-top: 1px solid var(--line);
  font-size: 12px;
  color: var(--muted);
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 24px;
}

.card {
  transition: transform 0.25s, box-shadow 0.25s;
}

.card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.dark {
  --bg: #121212;
  --panel: #1e1e1e;
  --text: #ececec;
  --muted: #a0a0a0;
  --line: #2a2a2a;
}

#theme {
  font-size: 20px;
  background: none;
  border: none;
  color: var(--text);
  cursor: pointer;
}

.post { max-width: 720px; margin: 0 auto; }
.post h1 { font-size: 36px; margin-bottom: 8px; }
.post .meta { color: var(--muted); margin-bottom: 24px; }
.post .cover { width: 100%; border-radius: 8px; }
.post .content { font-size: 17px; line-height: 1.8; }
.post .back { color: var(--mint); text-decoration: none; }
static/script.js
const button = document.getElementById("theme");

function apply(dark) {
  document.body.classList.toggle("dark", dark);
  button.textContent = dark ? "☀" : "☾";
}

apply(localStorage.getItem("theme") === "dark");

button.addEventListener("click", () => {
  const dark = !document.body.classList.contains("dark");
  localStorage.setItem("theme", dark ? "dark" : "light");
  apply(dark);
});
준비
localhost:8000 ↗