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
게시판

10 / 14

서버 데이터 렌더

지금 카드 세 개는 HTML에 손으로 박아 뒀죠. 글이 100개면 100번 복사해야 해요. 글 데이터는 서버가 들고 있고, HTML은 "글마다 카드 하나" 규칙만 적게 바꿔요.

app.py에 글 리스트를 만들어요. templates = ... 줄 아래에 넣으세요.

app.py
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",
    },
]

파이썬 리스트 안에 딕셔너리 세 개. 데이터베이스 대신 이걸 써요. 서버를 끄면 사라지지만 오늘은 충분해요. body는 다음 단계 상세 페이지에서 써요.

이 리스트를 HTML에 넘겨요. home 함수의 return을 바꾸세요.

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

세 번째 인자 딕셔너리가 HTML에서 쓸 수 있는 값이에요. 이제 HTML 안에서 posts라는 이름으로 리스트를 꺼내 쓸 수 있어요.

templates/index.html의 카드 세 개를 지우고, <div class="cards"> 안을 이렇게 바꿔요.

templates/index.html
    <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>
  • {% for post in posts %} ... {% endfor %} 사이를 글 개수만큼 반복해요. 파이썬 for문과 같아요.
  • {{ post.title }} 중괄호 두 개 안의 값을 그 자리에 찍어요.

실행하면 화면은 그대로예요. 대신 이제 app.py의 리스트에 딕셔너리를 하나 더 넣으면 카드가 네 개가 돼요. 해 보세요. 이미지는 thumb4.svg까지 있어요.

이 단계 전체 코드
app.py
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")

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})
templates/index.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>
    <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>
  </main>
  <script src="/static/script.js"></script>
</body>
</html>
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;
}
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 ↗