Flask 템플릿 엔진 Jinja2 파이썬 주요 모듈 소개 2020-06-14 신달수 0 댓글 0 289 # Jinja2 Library: Flask Template Engine (http://jinja.pocoo.org) # Types String, XML, HTML, JSON, Image, Video, etc # example {% extends "application.html" %} {% block body %} <ul> {% for song in songs %} <li><a href="{{song.url}}"> {{song.title}} </a></li> {% endfor %} </ul> {% endblock %} render_template("xx.html", username="Jade") {# comment #} trim_blocks from flask import render_template @app.route("/") def tmpl(): return render_template("index.html") # ./templates/index.html <pre> ttt 한글 {% if True %} TTT {% endif %}qqq </pre> # trim_blocks app config app.jinja_env.trim_blocks = True trim_blocks (Cont'd) # ./templates/index.html <pre> ttt 한글 {%- if True -%} TTT {%- endif -%}qqq </pre> # invalid {% - if True - %} escape # quotation escape {{ abc } efg }} {{ "}}>> <strong>Strong</strong>"}} or {{ '}}>> <strong>Strong</strong>' | escape }} # cf. safe string & striptags {{ "<strong>Strong</strong>" | safe}} {{ "<strong>Strong</strong>" | striptags}} # {% raw %} ~ {% endraw %} : display souce code {% raw %} {% if True %} TTT {% endif %} {% endraw %} Markup # from flask import Markup return render_template("index.html"), markup=Markup("<b>B</b>")) # Example: Markup() mu = Markup("<h1>iii = <i>%s</i></h1>") h = mu % "Italic" print("h=", h) return render_template("index.html", markup=Markup(h)) # Markup.escape() & unescape() bold = Markup("<b>Bold</b>") bold2 = Markup.escape("<b>Bold</b>") bold3 = bold2.unescape() print(bold, bold, bold3) => <b>Bold</b> <bgt;Bold</b> <b>Bold</b> FOR loop # {% for var in iter %} ... {% endfor %} {% for item in items %} ...item 처리.. {% endfor %} # Example lst = [ ("만남", "김건모"), ("만남", "노사연")] return render_template("index.html", lst=lst) <ul> {% for item in lst %} <li>{{item[0]}}: {{item[1]}}</li> {% endfor %} </ul> {% for title, name in lst %} <li>{{title}}: {{name}}</li> {% endfor %} loop object # for loop 속에서 기본으로 제공되는 object : '현재 for loop의 self' - loop.index: 1부터 시작하는 index 값 (cf. loop.index0) - loop.revindex: n-1 내림차순 index값 (cf. loop.revindex0) - loop.first: boolean(isThisFirstItem), loop의 첫번째인지의 여부 - loop.last: boolean(isThisLastItem), loop의 마지막인지의 여부 - loop.length: size # loop.cycle (특정 주기로 수행) <ul> {% for item in lst %} <li class="{{loop.cycle('aaa', 'bbb')}}">{{item[0]}}: {{item[1]}}</li> {% endfor %} </ul> for loop Filtering # data의 세번째 인자로 숨김 여부 추가 lst = [(1,"만남","김건모",false), (2,"만남","노사연",True), (3,"만남","익명",False)] return render_template("index.html", lst=lst) # index.html <ul> {% for rank, title, name, hide in lst if not hide %} <li class="{{loop.cycle('aaa', 'bbb')}}">{{title}}: {{name}}</li> {% endfor %} </ul> # for else {% for title, name, isShow in lst if not isShow %} <li class="{{loop.cycle('aaa', 'bbb', '')}}">{{title}}: {{name}}</li> {% else %} <li>There is no data.</li> {% endif %} for recursion # loop(data) a = (1, "만남1", "김건모", False, []) b = (2, "만남2", "노사연", True, [a]) c = (3, "만남3", "익명", False, [a,b]) d = (4, "만남4", "익명", False, [a,b,c]) return render_template("index.html", lst=[a,b,c,d]) # index.html <ul> {% for rank, title, name, hide, ref in lst recursive %} <li class="{{loop.cycle('aaa','bbb')}}"> <small>{{rank}} / {{loop.length}}</small> {{title}}: {{name}} {%- if ref -%} <ul class='sub'>{{ loop(ref) }}</ul> {%- endif -%} </li> {% endfor %} </ul> {% if condition %} ... {% endif %} # grammar {% if <Condition> %} ... {% endif %} # Example {% if lst %} {% for ... %} {% endif %} # if else (elif) {% if <Condition> %} ... {% elif <Other Condition> %} ... {% else %} ... {% endif %} parent's loop # set value {% set title = 'ABC' %} # access parent(outer) loop <ul> {% for rank, title, name, hide, ref in lst2 recursive %} <li> {{loop.index}} - {{title}}: {{name}} {%- if ref -%} {% set outer_loop = loop %} {% for ref_song in ref %} <p>{{outer_loop.index}} - {{loop.index}} : {{ ref_song[1] }}</p> {% endfor %} {%- endif -%} </li> {% endfor %} </ul> URL & Link # url_for('folder', filename='filename.ext') <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> # url_for('router-link') Copyright <a href="/tmpl">Happy Coding</a> Copyright <a href="{{ url_for('tmpl') }}">Happy Coding</a> Template Extends (block ~ endblock) # Base Template: 구조 및 자리 잡기용 (layout.html) <body> <h1>{% block <block-name> %}{% endblock %} - Layout Title</h1> </body> # extends the base layout html {% extends "layout.html" %} # mapping block : block 사용, 순서 무관! (in main.html) {% block <block-name> %}AAAAA{% endblock %} # super() : import html from same block-name {% block <block-name> %} {{ super() }} <p>TTT</p> {% endblock %} Duplicate Blocks # layout.html {% block outer_block %} <h3> {% block inner_block %}{% endblock inner_block %} - </h3> {% endblock outer_block %} # main.html {% block outer_block %} <p>111111111</p> {% block inner_block %}BBBBBB{% endblock inner_block %} {% endblock outer_block %} Template Extends (block ~ endblock) # Base Template: 구조 및 자리 잡기용 (layout.html) <body> <h1>{% block <block-name> %}{% endblock %} - Layout Title</h1> </body> # extends the base layout html (main.html) {% extends "layout.html" %} # mapping block : block 사용, 순서 무관! (in main.html) {% block <block-name> %}AAAAA{% endblock %} # super() : import html from same block-name {% block <block-name> %> {{ super() }} <p>TTT</p> {% endblock %} Duplicate Blocks # layout.html {% block outer_block %} <h3> {% block inner_block %}{% endblock inner_block %} - </h3> {% endblock outer_block %} # main.html {% block outer_block %} <p>1111111111</p> {% block inner_block %}BBBBB{% endlock inner_block %} {% endblock outer_block %} Use blocks in For loop # layout.html <h2>{% block title2 %}{% endblock %} - Layout Title2</h2> # main.html {% for item in [1,2] %} {% block title2 scoped %}<p>XXXXXXXXXXX {{item}}</p> {% endblock %} {% endfor %}