본문으로 바로가기

 

 

Templates — Flask Documentation (1.1.x)

Templates You’ve written the authentication views for your application, but if you’re running the server and try to go to any of the URLs, you’ll see a TemplateNotFound error. That’s because the views are calling render_template(), but you haven’

flask.palletsprojects.com

 

문서 읽어보기

 

 

 

위 Flask Tutorial 코드에서 가져와 보았습니다.

 

{% ~ %} 이런 부분들이 눈에 띄네요.

if else elseif , 아마도 해당 html 로 전송된 g.user 라는 데이터의 유무에 따라 레이아웃을 달리하겠다는 거겠네요.

<!doctype html>
<title>{% block title %}{% endblock %} - Flaskr</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<nav>
  <h1>Flaskr</h1>
  <ul>
    {% if g.user %}
      <li><span>{{ g.user['username'] }}</span>
      <li><a href="{{ url_for('auth.logout') }}">Log Out</a>
    {% else %}
      <li><a href="{{ url_for('auth.register') }}">Register</a>
      <li><a href="{{ url_for('auth.login') }}">Log In</a>
    {% endif %}
  </ul>
</nav>
<section class="content">
  <header>
    {% block header %}{% endblock %}
  </header>
  {% for message in get_flashed_messages() %}
    <div class="flash">{{ message }}</div>
  {% endfor %}
  {% block content %}{% endblock %}
</section>

 

그런데 이 부분, {% block ~ %} {% endblock %} 은 한 눈에 이해되진 않았습니다.

<title>{% block title %}{% endblock %} - Flaskr</title>
...
<section class="content">
  <header>
    {% block header %}{% endblock %}
  </header>
  {% for message in get_flashed_messages() %}
    <div class="flash">{{ message }}</div>
  {% endfor %}
  {% block content %}{% endblock %}
</section>

 

설명을 읽어보니 위의 코드는 base.html template 으로 다른 템플릿들에 오버라이드될 블록을 정의한 것이라고 합니다.

편하게, 해당 위치에 접근하기 위해서라고 이해하겠습니다.

 

 

register.html 이라는 템플릿이구요.

base 템플릿을 상속받아서 각 블록을 재정의 합니다.

{% extends 'base.html' %}

{% block header %}
  <h1>{% block title %}Register{% endblock %}</h1>
{% endblock %}

{% block content %}
  <form method="post">
    <label for="username">Username</label>
    <input name="username" id="username" required>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" required>
    <input type="submit" value="Register">
  </form>
{% endblock %}

 

실습 해보기

 

같은 경로에 templates 디렉터리 생성하고 안에 템플릿을 생성합니다.

render_template 모듈을 임포트하고 return render_template('template file')

하면 html 을 반환합니다. 

 

 

 

Flask

from flask import Flask, render_template

app = Flask(__name__)

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


@app.route('/info')
def info():
    return render_template('info.html')

if __name__ == '__main__':
    app.run(debug=True)

 

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jvvp</title>
</head>
<body>
    <h1>Jvvp [ {% block title %}{% endblock %} ] Tistory</h1>
    <p>{% block desc %}안녕하세요? 오늘은 화요일입니다.{% endblock %}</p> 
</body>
</html>

 

index.html

{% extends 'base.html' %}

{% block title %} 메인 페이지입니다. {% endblock %}

 

결과는 다음과 같이 나옵니다.

block 외부는 무시하는 줄 알았으나, block 이 속한 태그로(h1) 안의 내용은 다 출력이됩니다.

 

 

소개 페이지는 desc block 을 재정의해봅니다.

{% extends 'base.html' %}

{% block title %} 소개 페이지입니다. {% endblock %}
{% block desc %}안녕하세요? 내일은 수요일입니다.{% endblock %}