Flask 에서는 render_template 이라는 메소드로 html 파일들을 불러올 수 있는 방법
해당 함수는 기본적으로 프로젝트 폴더 내에 'templates' 라는 이름의 폴더를 기본 경로로 설정
따라서 먼저 templates 폴더를 만들고 내부에 html 파일들을 모아두면 손쉽게 사용
flask_app
├── __init__.py
└── routes
└── user_routes.py
└── templates
└── index.html
# templates 폴더에 다음과 같은 index.html 파일
<html>
<head>
<title>
New HTML Page
</title>
</head>
<body>
<h1>I am in templates folder</h1>
</body>
</html>
==>
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
만약에 templates 폴더 내에 또다른 폴더에 있다해도 경로는 templates 폴더 기준으로 잡아줘야함
(... 생략 ...)
@app.route('/main')
def main():
return render_template('main/main.html')
# CSV 파일 경로와 임시 파일 경로입니다.
CSV_FILEPATH = os.path.join(os.getcwd(), 'mini_flask_app', 'users.csv')
os.path.join(os.path.dirname(__file__), 'ㅁㄴㅇㅁㄴㅇ')
==> app.py 파일 위치를 기준으로 원하는 파일을 찾을 수있음.
or
curr_filepath = os.path.dirname(__file__)
with open(f'{curr_filepath}/users.csv', newline='') as f:
os.getcwd() ==> 현재 어디있는지
Jinja 표현
<body>
<h1>{{ title }}</h1>
</body>
- {% ... %} : 구문에 사용이 됩니다 (if, for 등).
- {{ ... }} : 템플렛 결과 (html) 에 출력할 표현입니다 (변수 등).
- {# ... #} : 주석 처리할 때 사용됩니다.
@app.route('/')
def index():
apple = 'red'
apple_count = 10
return render_template('index.html', fruit_color=apple, number=apple_count)
# templates 폴더에 index.html에서 지정
<body>
<h2>Apple is {{ fruit_color }}</h2>
<h2>{{ apple_count }} 개의 과일이 있습니다.</h2>
</body>
or
@app.route('/<item>')
def index(item):
return render_template('index.html', item=item)
* item이라는 파라미터로 생성을 했다면 html에서도 해당 파라미터로 변경해줘야함
# templates 폴더에 index.html에서 지정
<body>
<h1>{{ item }}</h1>
</body>
Jinja 기능들
*객체 태그
var=[1, 2, 3]
==> {{ var }}
fruits = { 'apple' : 'red', 'banana' : 'yellow' }
==> {{ fruits.apple }}
vegetables = [ 'cucumber', 'spinach' ]
==> {{ vegetables[0] }}
* if 구문
{% if True %}
<h1>It is True</h1>
{% elif False %}
<h1>It is False</h1>
{% else %}
<h1>It is not True</h1>
{% endif %}
* for 구문
item_list 라는 리스트가 ['book', 'keyboard', 'window']
{% for item in item_list %}
<p>{{ item }}</p>
{% endfor %}
loop 속성설명
loop.index | 반복 순서 1부터 1씩 증가 |
loop.index0 | 반복 순서 0부터 1씩 증가 |
loop.first | 반복 순서가 처음일 경우 True 아니면 False |
loop.last | 반복 순서가 마지막일 경우 True 아니면 False |
인덱스를 파악할 때에 유용한 loop.index0
{% for item in item_list %}
<p>인덱스 : {{ loop.index0 }}, 이름 : {{ item }}</p>
{% endfor %}
Jinja 상속
- {% extends %}
- {% block %} ... {% endblock %}
@app.route('/main')
def index(item):
return render_template('child.html')
# base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
child.html 파일을 base.html 파일과 같은 경로에 생성한 뒤에 base.html 파일 내용을 상속받고 싶다면
# child.html
{% extends "base.html" %} ==> base.html 상속 / 상속은 첫 줄에 위치해야 합니다.
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }} ==> 'child.html' 처럼 부모의 'head' 블록 내용을 가져오고 싶을 때
<h1>자식 블록에서 출력한 h1 입니다.</h1>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
base.html에서 생성한 블럭이름을 child.html 에서도 똑같이 적는다.
child.html에서 수정한 내용은 base.html에 해당 블럭( block / endblock )부분에 들어감
Jinja 는 상속에서 부모와 자식 구분이 없습니다. 그렇기 때문에 한번 상속을 하면 부모 파일의 모든 것을
상속하게 됩니다.
따라서 자식 HTML 파일에서 뭔가를 작성하게 된다면 부모의 파일 내용 이후에 작성이 됩니다.
==> 부모 먼저 나오고 그다음 자식이 나옴
자식이 부모 블록의 내용을 사용하려면 파이썬과 비슷하게 super 를 통해서 사용 가능합니다.
2번 상속된 파일이 가장 상위 부모의 내용을 접근하기 위해서는 super.super() 로도 접근 가능합니다.
'데이터 엔지니어링(DE) > Application과 API' 카테고리의 다른 글
bootstrap (0) | 2021.07.24 |
---|---|
Flask (0) | 2021.07.24 |
API / HTTP (0) | 2021.07.24 |
댓글