템플릿 보여주기1
Flask를 통해서 HTML 문서를 생성할 수 있다.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index() :
return '<html><body><h1>hello</h1></body></html>' # 직접 html를 렌더링할 수 있다.
if __name__ == '__main__' :
app.run()
하지만 파이썬 코드 내부에서 HTML 코드를 작성하는 것은 유지보수 측면에서 매우 힘들다. 따라서 Flask에서는 Jinja2 템플릿엔진을 사용한다. render_template()를 사용하면 html 문서를 렌더링할 수 있다.
웹 템플릿 시스템
웹 템플릿 시스템은 동적으로 변수 데이터를 삽입할 수 있는 HTML 스크립트의 디자인은 참조한다.
데이터베이스에 우리가 보여주고 싶은 자료인 데이터 원본이 있다. 이 데이터를 효과적으로 전달하기 위하여 미리 만들어둔 html 스크립트를 사용할 것이다. 미리 준비해둔 HTML 스크립트에 있는 지정된 변수에 데이터베이스에서 가져온 데이터를 넣어서 보여주면 보기 좋은 형태로 구성된 웹 페이지를 볼 수 있게 된다.
미리 준비해둔 HTML 스크립트가 바로 웹 템플릿이고 데이터 원본과 웹 템플릿을 동적으로 연결하는 작업을 템플릿 엔진이 담당한다. 우리가 쓰는 Flask에서는 jinja2가 템플릿 엔진이다. 웹 템플릿은 변수와 (jinja2에서는 python의)표현식의 placehorder가 배치된 HTML 문법을 포함하고 있다.
다음과 같이 변수값을 출력할 수 있다.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>') # 라우팅할 URL, user 인자로 값이 전달된다.
def hello_name(user) :
return render_template('hello.html', name=user)
# hello.html 스크립트를 렌더링한다.
# name으로 user의 값이 전달된다
if __name__ == '__main__' :
app.run()
<!doctype html>
<html>
<body>
<h1>h3llo {{name}}</h1> <!--{{name}} pacehorlder를 user의 값으로 대체된다-->
</body>
</html>
이 때 디렉토리 구조에 유념해야한다. Flask는 templates 디렉토리에서 템플릿을 찾기 때문에 모듈로 어플리케이션을 개발했다면 디렉토리는 그 모듈의 옆에 위치하고, 패키지로 개발했다면 그 패키지 안에 위치한다
case1 : 모듈
/application.py
/templates
/hello.html
case2 : 패키지
/application
/__init.py
/templates
/helly.html
결과는 다음과 같다
템플릿 보여주기2
조건문을 사용할 수 있다.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/score/<int:num>') # 라우팅할 URL, num 인자로 값이 전달된다
def result(num) :
return render_template('score.html', score=num) # score.html를 렌더링한다 # score로 num의 값이 전달된다
if __name__ == '__main__' :
app.run()
<!doctype>
<html>
<body>
{% if score >= 50 %} <!--조건문-->
<h1>PASS</h1>
{% else %} <!--조건문-->
<h1>FAIL</h1>
{% endif %} <!--조건문-->
</body>
</html>
반복문을 사용할 수 있다.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result') # 라우팅할 URL
def result() :
dict = {'a':40, 'b':60, 'c':80} # 객체 선언
return render_template('score2.html', result=dict) # result로 dict이 전달된다
if __name__=='__main__' :
app.run()
<!doctype html>
<html>
<body>
<table border=1 style='border-collapse:collapse'>
{% for key, value in result.items() %} <!--객체를 반복한다-->
<tr>
<th> {{key}} </th> <!---key 값을 출력한다-->
<td> {{value}} </td> <!--value 값을 출력한다-->
</tr>
{% endfor %}
</table>
</body>
</html>
'기초공부 > WEB' 카테고리의 다른 글
[PHP]mysqli_query (0) | 2019.05.31 |
---|---|
[PHP]mysqli_connect (0) | 2019.05.31 |
[Flask]빠르게 보여주기 - 정적 파일 (0) | 2019.05.20 |
[Flask]빠르게 시작하기 - HTTP 메소드 (0) | 2019.05.20 |
[Flask]빠르게 시작하기 - URL 생성 (0) | 2019.05.20 |