Python Flask 혹은 Django를 사용하게 되면 HTML에 Jinja2 문법을 사용하여 추가적인 작업을 수행할 수 있습니다.
여기서 Jinja2의 For문을 사용하는 방법을 알아보도록 하겠습니다.
Jinja2를 사용할 때 Python Flask로 다음과 같이 작성했다고 합시다.
예제 소스
@app.route('/', method=['GET'])
def hello_kkamikoon():
myList = []
for i in range(0, 10):
myList.append('count : %d' % i)
return render_template('/app/templates/hello_kkamikoon.html', myList=myList)
위의 파이썬 소스를 실행시켰다는 가정하에 이제 HTML 소스를 보시겠습니다.
<!--source name : hello_kkamikoon.html -->
<!--source dir : /app/templates/hello_kkamikoon.html -->
<html lang="ko">
<head>
<title>kkamikoon Jinja2 for</title>
>
</head>
<body>
<ul>
{% for ml in myList %}
<li> {{ml}} </li>
{% endfor %}
</ul>
</body>
</html>
결과
<!--source name : hello_kkamikoon.html -->
<!--source dir : /app/templates/hello_kkamikoon.html -->
<html lang="ko">
<head>
<title>kkamikoon Jinja2 for</title>
>
</head>
<body>
<ul>
<li> count : 0 </li>
<li> count : 1 </li>
<li> count : 2 </li>
<li> count : 3 </li>
<li> count : 4 </li>
<li> count : 5 </li>
<li> count : 6 </li>
<li> count : 7 </li>
<li> count : 8 </li>
<li> count : 9 </li>
</ul>
</body>
</html>
myList에 있는 값이 그대로 html로 옮겨져서 반복되는 것을 볼 수 있습니다.
'WEB PROGRAMMING > Jinja2' 카테고리의 다른 글
| [Jinja2] break문 사용하는 방법 (0) | 2019.02.12 |
|---|---|
| [Jinja2] 배열(리스트) 인덱스 사용하는 방법 (0) | 2019.02.06 |