Flask 템플릿 사용하기
지금까지는 Flask에서 문자열만 반환했다.
하지만 실제 웹 개발에서는 HTML 파일을 화면에 보여줘야 한다.
Flask에서는 템플릿 엔진으로 Jinja2를 사용한다.
HTML 파일을 templates 폴더에 저장하고,render_template() 함수를 통해 화면에 출력한다.
Flask 템플릿 사용 흐름은 다음과 같다.
1. 프로젝트 폴더 안에 templates 디렉토리 생성
2. HTML 파일 작성
3. render_template()로 HTML 반환
Flask는 기본적으로 templates 폴더를 자동으로 인식한다.
기본 템플릿 구조
폴더 구조 예시
project/
├── app.py
└── templates/
└── index.html
index.html 예시
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello Flask</h1>
</body>
</html>
Flask 코드
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
이제 브라우저에 HTML 페이지가 출력된다.
템플릿에 변수 전달하기
Flask에서는 HTML에 값을 전달할 수 있다.
@app.route("/user/<name>")
def user(name):
return render_template("user.html", username=name)
user.html
<h1>Hello {{ username }}</h1>
{{ 변수명 }} 형태로 HTML 안에서 사용할 수 있다.
조건문과 반복문
Jinja2에서는 조건문과 반복문도 사용할 수 있다.
조건문
{% if username %}
<h1>Hello {{ username }}</h1>
{% endif %}
반복문
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html", name="Minho")
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello {{ name }}</h1>
</body>
</html>