Application/Jinja

Jinja Templates

DS지니 2021. 3. 22. 18:46
728x90
반응형

 

jinja- 템플렛 디자이너 doc

flask- 템플렛 사용법

Jinja Templates 

Flask 로 정적인 페이지를 만든다면 Jinja 템플렛은 페이지를 동적인 페이지로 변신시켜주는 Web Template Engine 입니다. 템플렛 엔진은 맞춤형 웹페이지를 자동으로 생산할 수 있도록 도와줍니다.

 

예를 들어 오늘의 날짜를 페이지에 표시하고 싶을 때나 검색창을 사용하고 싶을 때 등에 유용합니다.

 

Flask 패키지 설치 안에 포함되어 있기 때문에 pip install flask를 했다면 따로 설치 할 필요는 없습니다.

 

더보기

<기본사용법>

pip install Jinja2

>>> from jinja2 import Template

>>> template = Template('Hello {{ name }}!')

>>> template.render(name='John Doe')

u'Hello John Doe!'

2. Flask 템플렛 사용법

1. html 파일 불러오기

# 폴더 작성
templates
	|_index.html


# template 코드
from flask import Flask, render_template

app = Flask(__name__)

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

* html 파일

# index.html

<html>
  <head>
    <title>
      New HTML Page
    </title>
  </head>
  <body>
    <h1>I am in templates folder</h1>
  </body>
</html>

 

2.1 파일 경로 주의 할 점

만약 templates 폴더 내에 또다른 폴더에 파일이 있다고 해도 경로는 templates 폴더 기준로 잡아줘야합니다.

# 폴더안의 폴더
templates
 |	
main
   |_main.html
   
   
# template 경로
from flask import Flask, render_template

app = Flask(__name__)

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

 

3. Jinja 표현

'{ }' 중괄호 사용

<!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>

렌더링 방식 4가지

  • {% ... %} : 구문에 사용이 됩니다 (if, for 등).
  • {{ ... }} : 템플렛 결과 (html) 에 출력할 표현입니다 (변수 등).
  • {# ... #} : 주석 처리할 때 사용됩니다.
  • #  ... ##Line Statements

1) Flask - Jinja 변수 전달

@app.route('/')
def index():
    user_id = 'abc'
    user_pwd = 100
    return render_template('index.html', id=user_id, pwd=suer_pwd)
    
    
# html 파일은 아래와 같이 작성
<body>
  <h2>user_id is {{ id }}</h2>
  <h2>{{ pwd }}를 입력하였습니다.</h2>
</body>

 

2) 변수 - 딕셔너리, 리스트

fruits = { 'apple' : 'red' , 'banana' : 'yellow' }
vegetables = [ 'onion', 'carrot' ]


{{ fruits.apple }}

{{ vegetables[0] }}

 

3) If 구문

<input>

<div>
    {% if True %}
        yay
    {% endif %}
</div>
{% if True %}
<h1>It is True</h1>
{% elif False %}
<h1>It is False</h1>
{% else %}
<h1>It is not True</h1>
{% endif %}

 

 

4) loof 구문

seq =[1,2,3,4,5,6,7,8,9]


{% for item in seq -%}
    {{ item }}
{%- endfor %}

output : 123456789

 

{% for item in item_list %}
<p>인덱스 : {{ loop.index0 }}, 이름 : {{ item }}</p>
{% endfor %}
loop 속성 설명
loop.index 반복 순서 1부터 1씩 증가
loop.index0 반복 순서 0부터 1씩 증가
loop.first 반복 순서가 처음일 경우 True 아니면 False
loop.last 반복 순서가 마지막일 경우 True 아니면 False

 

5) 상속(Inheritance)

- Base Template

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
</head>
<body>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
        {% endblock %}
    </div>
</body>
</html>

- Child Template

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
      Welcome to my awesome homepage.
    </p>
{% endblock %}

 

  • {% extends "base.html" %} : 상속할 때 첫줄에 나오는 코드. 상속할 파일 입력
  • {{ super() }} : 상속할 코드. 놓고 싶은 위치에 입력
  • {% block 블락의이름 %} ... {% endblock %} : 그 외 추가할 내용 입력

- 상속 여러번 하기

# parent.tmpl
body: {% block body %}Hi from parent.{% endblock %}

# child.tmpl
{% extends "parent.tmpl" %}
{% block body %}Hi from child. {{ super() }}{% endblock %}

# grandchild1.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild1.{% endblock %}

# grandchild2.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}
  • Rendering child.tmpl will give body: Hi from child. Hi from parent.
  • Rendering grandchild1.tmpl will give body: Hi from grandchild1.
  • Rendering grandchild2.tmpl will give body: Hi from grandchild2. Hi from parent.

 

6) 그 외 사이트 참고

728x90
반응형