python - Web13
python flask, html, jinja2
>>jinja2: http://jinja.pocoo.org/docs/2.10/
1. 템플릿을 사용해 화면에 출력하기
@app.route('/') def home(): data = [ {'rank':1, 'national':"한국"}, {'rank':2, 'national':"미국"}, {'rank':3, 'national':"일본"} ] return render_template('index.html', items=data): data라는 이름을 가진 리스트를 만든다. 리스트 내용은 사전으로 작성했다. render_template를 사용해 index.html을 통해 화면을 그리게한다. items=data로 인자를 줘 index.html로 인자를 전한다. 인자는 여러개를 넣을 수 있다. items는 index.html에서 사용할 인자, data는 현재 파일에서 사용하는 변수다.
2. 인자를 받아 html파일로 화면에 출력하기
<body> {{items}} <table border="1" cellspacing="0"> <thead> <tr> <td>랭킹</td> <td>국가</td> </tr> </thead> {% for item in items %} <tr> <td>{{item["rank"]}}</td> <td>{{item["national"]}}</td> </tr> {% endfor %} </tbody> </table> </body>
{{items}}
:jinja2 사용. jinja2에서 변수를 사용할 떄는 {{}}안에 변수를 집어 넣는다. .py파일에서 items에 data를 전달했기 때문에 items는 data와 동일한 값을 가진다.<table border="1" cellspacing="0">:table태그를 사용해 테이블을 만든다. border은 선의 굵기를 의미하고 cellspacing은 cell사이의 간격(픽셀)을 지정한다.
{% for item in items: %}
<tr>
<td>{{item["rank"]}}</td>
<td>{{item["national"]}}</td>
</tr>
{% endfor %}
:jinja2는 for문을 사용할 수 있다. for의 조건문은 {%%}안에 집어 넣고 for문의 마지막은 {%endfor%}로 구분한다. 조건문과 endfor로 둘러싸인 코드들이 반복된다. jinja2의 주석은 {##}이다. html의 주석과 다른 점이 있다면 페이지 소스보기에서 보이지 않는다.전체코드
1. .pyfrom flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): data = [ {'rank':1, 'national':"한국"}, {'rank':2, 'national':"미국"}, {'rank':3, 'national':"일본"} ] return render_template('index.html', items=data) if __name__ == '__main__': app.run(debug=True)
2. index.html
<!DOCTYPE html> <html> <head></head> <body> {{items}} <table border="1" cellspacing="0"> <thead> <tr> <td>랭킹</td> <td>국가</td> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{item["rank"]}}</td> <td>{{item["national"]}}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
댓글
댓글 쓰기