📝 렌더링 템플릿

렌더링(Rendering) : 마크업 언어를 브라우저(Client)에 보여주기 위한 과정

플라스크 내에서 html 파일을 사용해 웹 사이트를 제작할 수 있다. 이 때 사용하는 것이 렌더링 템플릿이다.
html 코드들을 플라스크내에 사용하는 것보다 파일을 따로 만들어 라우팅하는 방법이 유지보수에서 이롭다.

플라스크는 render_template( )을 이용해 html 파일을 렌더링하여 브라우저에 보여줄 수 있습니다.

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

hello 함수의 URL에 접근할 때, hello.html을 반환하며 해당 html 파일의 매개변수 name에 함수의 매개변수인 name을 전달한다.

 

📝 Jinja2

렌더링 템플릿을 통해 화면을 출력할 때 html에서는 아래와 같은 Jinja2 문법으로 해당 내용을 띄울 수 있습니다.

{% for row in rows %}
<tr>
    <td>{{ loop.index }}</td>
    <td>{{ row[0] }}</td>
    <td>{{ row[1] }}</td>
</tr>
{% endfor %}


<!--
	일반적인 형식
    
	{% if문 or for문 %}
    
    {{ 변수나 표현식}}
    	...	....
    {% endif 또는 endfor %}
-->

Docs : jinja.palletsprojects.com/en/2.11.x/templates/

 

Template Designer Documentation — Jinja Documentation (2.11.x)

This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible, the configuration from the application can be slightly different from t

jinja.palletsprojects.com

 

📝 블루 프린트

Flask의 요청으로 URL을 생성 할 때 화면을 출력하는 함수를 블루 프린트와 연결한다.

블루 프린트는 웹 애플리케이션의 개체를 미리 요구하지 않고 기능을 정의할 수 있다.
또한, 파일을 여러개로 나누어 유지 보수 측면에서 매우 효과적으로 개발할 수 있게끔 할 수 있다.

블루 프린트 없이 flask 웹 애플리케이션을 만들 수 있다.
하지만 여러 기능이 포함된 웹 애플리케이션을 제작하고자 한다면 블루프린트를 사용하는 것을 권장한다.

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

simple_page = Blueprint('simple_page', __name__,
                        template_folder='templates')

@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
    try:
        return render_template('pages/%s.html' % page)
    except TemplateNotFound:
        abort(404)

@simple_page.route 장식자를 이용해 함수를 바인딩하면 구현한 show() 함수를 통해 블루 프린트가 동작하게 된다.
만약 블루 프린트 등록하려면 아래와 같이 register_blueprint() 함수를 이용하면 된다.

from flask import Flask
from yourapplication.simple_page import simple_page

app = Flask(__name__)
app.register_blueprint(simple_page)

 

📝 예제 ) 간단한 게시판 ( CRUD )

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)
board = []

# 게시판 내용 조회 (Read)
@app.route('/')
def index():
    return render_template('list.html', rows=board)

# 게시판 내용 추가 (Create)
@app.route('/add',methods=["POST"])
def add():
    if request.method == "POST":
        name = request.form["name"]
        context = request.form["context"]
        board.append([name,context])
        return redirect(url_for("index"))
    else:
        return render_template("list.html", rows=board)

# 게시판 내용 갱신 (Update)
@app.route('/update/<int:uid>', methods=["GET","POST"])
def update(uid):
    if request.method == "POST":
        index = uid - 1
        name = request.form["name"]
        context = request.form["context"]
        
        board[index] = [name,context]   # 기존의 board내용에 덮어쓰기
        return redirect(url_for("index"))
    else:
        return render_template("update.html",index=uid,rows=board)

# 게시판 내용 삭제 (Delete)
@app.route('/delete/<int:uid>')
def delete(uid):
    index = uid - 1
    del board[index]

    return redirect(url_for("index"))


if __name__ == '__main__':
    app.run(debug=True)
<!-- ./template/list.html -->

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus®">
    <meta name="Author" content="">
    <meta name="Keywords" content="">
    <meta name="Description" content="">
    <title>SQLite3 게시판 등록</title>

    <style type="text/css">
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <h3>게시판</h3>
    <h4>추가</h4>
    <form action="/add" method="POST">
        이름<br>
        <input type="text" name="name" /><br>
        내용<br>
        <input type="text" name="context" style="text-align:center; width:400px; height:100px;" /><br><br>
        <input type="submit" value="게 시" /><br>
    </form>
    <h4>목록보기</h4>
    <table border=1 width="600" align="center">
        <thead>
            <td>목차</td>
            <td>이름</td>
            <td>내용</td>
            <td>수정, 삭제</td>
        </thead>
        {% for row in rows %}
        <tr>
            <td>{{ loop.index }}</td>
            <td>{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
            <td><a href="{{url_for('update', uid = loop.index)}}">수정</a> <a
                    href="{{url_for('delete', uid = loop.index)}}">삭제</a></td>
        </tr>
        {% endfor %}
    </table>
</body>

</html>
<!-- ./templates/update.html -->

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus®">
    <meta name="Author" content="">
    <meta name="Keywords" content="">
    <meta name="Description" content="">
    <title>SQLite3 게시판 등록</title>

    <style type="text/css">
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <h3>게시판</h3>
    <h4>수정</h4>
    <form action="/update/{{index}}" method="POST">
        이름<br>
        <input type="text" name="name" /><br>
        내용<br>
        <input type="text" name="context" style="text-align:center; width:400px; height:100px;" /><br><br>
        <input type="submit" value="수 정" /><br>
    </form>
    <h4>기존</h4>
    <table border=1 width="600" align="center">
        <thead>
            <td>목차</td>
            <td>이름</td>
            <td>내용</td>
        </thead>
        <tr>
            <td>{{ index}}</td>
            <td>{{ rows[index-1][0] }}</td>
            <td>{{ rows[index-1][1] }}</td>
        </tr>
    </table>
</body>

</html>

[ 출처 : elice ]

 

728x90
반응형

+ Recent posts