3. 템플릿 렌더링

템플릿 렌더링

Flask에서는 render_template()을 사용해서 템플릿 렌더링을 할 수 있다.

템플릿 렌더링이란 서버의 Python 코드에서 생성한 변수나 값을 뼈대인 HTML 코드에 삽입하여 최종 HTML 문서를 만드는 과정을 말한다.

템플릿 렌더링 예시 살펴보기

app.py

import datetime
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/simple_page')
def get_simple_page():
    dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return render_template('simple_page.html', current_time=dt)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=31337)

8번 라인과 10번 라인에서 볼 수 있듯이 **render_template()**의 두 번째 매개변수인 current_time에 dt라는 변수가 전달되도록 수정되었다. 이는 dt 라는 데이터를 current_time이라는 이름으로 simple_page.html 문서에 전달하겠다는 의미이다. dt 변수는 9번 라인을 살펴보면, 현재의 시각을 문자열 형태로 담고 있는 변수이다.

templates/simple_page.html

<!DOCTYPE html>
<html>
<head>
  <title>My Simple Web Page</title>
</head>
<body>
  <h1>Explore the World of HTML!</h1>
  <p>Greetings from the Web!</p>
  <h2>{{ current_time }}</h2>
</body>
</html>

9번 라인에서 볼 수 있듯이 {{ current_time }} 라는 문구를 <h2> 태그로 출력하는 요소가 추가된 모습이다.

이는 앞서 app.py에서 render_template()을 통해 전달받은 인자인 current_time을 {{ current_time }} 위치에 그대로 삽입하겠다는 의미이다.

브라우저 테스트 결과

위 app.py와 simple_page.html로 웹 서버를 연 후 브라우저로 http://127.0.0.1:31337/simple_page에 접속하면 다음과 같은 웹 페이지가 나온다. 2025-12-11 07:44:06이라는 현재 시각을 나타내는 문자열이 웹 페이지에 출력되는 모습이다.

브라우저에서 테스트한 결과

앞서 설명하였듯이 app.py에서 render_template()을 통해 현재 시각을 나타내는 문자열을 current_time이라는 이름으로 simple_page.html에 전달했고, simple_page.html은 전달받은 current_time을 이중 중괄호로 감싼 {{ current_time }} 이라는 특수한 문구를 통해 삽입하였기 때문에 최종 HTML 문서에 현재 시각을 나타내는 문자열이 출력되는 원리이다.