Flask에서는 HTML을 렌더링(rendering)하기 위하여 신사2(Jinja2)를 사용한다.
Rendering Template
template를 rendering 하기 위해서 render_template 함수를 사용한다. 첫번째 parameter는 파일 이름을 나타내며 이후의 parameter는 key/value 형태의 변수를 전달 한다.
template/index.html
<h1>Hello World</h1>
template/user.html
<h1>Hello, {{ name }}</h1>
hello.py
Variables
{{ name }} 는 Jinja2에서 변수를 나타낸다. render_template 의 parameter 로 전달 된 변수가 사용 되는 것이다.
Jinja2에서는 list, dictionary, object 등 어떤 형태의 type 도 지원한다.
Variable Filters
Variables은 filters에 의해 수정 될 수 있다. Jinja2에서 지원하는 filters은 다음과 같은 것들이 있다.
Hello, {{ name | capitalize }} 와 같이 파이프라인(|) 을 사용하여 호출 할 수 있다.
safe filter는 중요한 필터이다. Jinja2에서 각 변수들은 security 를 위하여 변경된다. 예를 들어 어떤 변수 값이 '<h1>Hello</h1> 이라면 '<h1>Hello</h1>' 로 표시 된다. safe filter는 이러한 변형을 없애는 escape filter 이다.
Control Structures
if 문
for 문
macro 문
macro는 다른 파일에 있는 함수도 불러 사용할 수 있다.
{% import 'macro.html' as macro %}
<ul>
{% for comment in comments %}
{{ macro.render_comment(comment) }}
{% endfor %}
</ul>
include를 사용하여 모든 template를 불러 올 수도 있다.
{% include 'common.html' %}
template 의 상속
base.html
위와 같이 base.html이 있을 경우 각각의 block에 extents를 통하여 상속을 받아 사용한다.
'디지털 양피지 > Flask' 카테고리의 다른 글
Flask - Custom Filters (0) | 2016.01.05 |
---|---|
Flask - Web Form (0) | 2015.12.18 |
Flask - Custom Error Pages / Links / Static Files /Time (0) | 2015.12.18 |
Flask - Twitter Bootstrap Integration with Flask-Bootstrap (0) | 2015.12.17 |
Flask - Basic Application Structure (0) | 2015.12.16 |