Python/Flask

[Flask] Jinja 정리

yubi5050 2022. 5. 7. 14:28

Flask에서는 Jinja2 라는 템플릿 엔진을 통해 웹 화면 구성을 보다 동적으로 가능하게 함

애플리케이션 내 변수, 조건문, 반복문 등을 랜더링 함

 

Jinja2 홈페이지

https://jinja.palletsprojects.com/en/3.1.x/

 

Jinja — Jinja Documentation (3.1.x)

 

jinja.palletsprojects.com

 

예제 1. 변수 / 변수 함수 / 조건문 적용

{{변수명}}, {{변수명 | 함수}}

{% if %}, {% elif %}, {% else %}, {% endif %}

# app.py
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    parameter = 'parameter~~1'
    condition = 20 
    return render_template("index.html", params = parameter, condition=condition)

if __name__ == '__main__':
    app.run(debug=True)
# index.html
<!DOCTYPE html>
<html><body>
    <h1>변수 & 함수 사용</h1>
    {{params}}, {{params|length}}

    <h2> 조건문</h2>
    {% if condition < 20 %}
        <p>{{ condition }}은 20보다 작다.</p> 
    {% elif condition > 20 %}
        <p>{{ condition }}은 20보다 크다.</p> 
    {% else %}
        <p>{{ condition }}은 20이다.</p> 
    {% endif %}
</body></html>

 


 

예제 2. 반복문 

{% for i in range(3) %} , {%endfor%}

# app.py
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    # List 
    animal_list = ['호랑이','사자','표범']
    fruit_dict = { # Dict
        '사과':35,
        '배':20,
        '귤':25
    }
    # List 내 Dicionary
    multi_list = [
        {'movie':'a', 'rating':30},
        {'movie':'b', 'rating':10},
        {'movie':'c', 'rating':20},
    ]
    return render_template("index.html", 
                            fruits = fruit_dict, 
                            animals = animal_list,
                            multis = multi_list)

if __name__ == '__main__':
    app.run(debug=True)
# index.html
<!DOCTYPE html>
<html><body>
    <h1>1. 반복문</h1>
    <ul>
    {% for an in animals %}
        <li>{{ an }}</li>
    {% endfor%}
    </ul>

    <h1>2. Dicionary 반복문</h1>
    <ul>
        {% for key, value in fruits.items() %}
            <li>{{ key }} : {{ value }}개</li>
        {% endfor%}
    </ul>

    <h1>3. List 내 Dicionary Value 기준 반복문</h1>
    <ul>
        {% for attr in multis | sort(attribute='rating')%}
            <li>{{ attr }}</li>
        {% endfor%}
    </ul>
</body></html>

 


 

예제 3. 템플릿 상속 (Inheritance)

웹 사이트 header, footer 레이아웃의 일관성을 유지 할 때 템플릿 상속 기능 사용

자식은 block 부분만 완성하고 나머지 부분은 부모의 모든 것을 자식이 가져간다고 생각

아래 예시는 grand_father(nav) => father(body) => children(본문) 이중 상속 예시임

 

작성 방법 - 부모 문서 (grand_father.html)

- 자식이 있을 곳 {% block content %} {% endblock %} 로 명시

 

작성 방법 - 자식 문서 (father.html, children.html)

- 윗 부분에 {% extends 부모문서이름 %} 명시

- 아랫 부분에 {% block content %} {% endblock %} 사이 내용 작성

# app.py
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template("children.html")

if __name__ == '__main__':
    app.run(debug=True)
# grand-father.html
<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <nav style="Background-color:Blue; height:150px;">Nav Header 입니다.</nav>
    <body>
        {% block content1 %}{% endblock %}
    </body>
 </html>
# father.html
{% extends 'grand_father.html' %}
{% block content1 %}
    <div style='Background-color:aqua;'>
        <p>This is father html!!</p>
        {% block content2 %} {% endblock%}
    </div>
{% endblock %}
# children.html
{% extends 'father.html' %}
{% block content2 %}
    <div style="Background-color:yellow;">
        <p>This is son html!!</p>
    </div>
{% endblock %}