Çöó½ºÅ©ÀÇ Jinja2 ÅÛÇø´ ¹®¹ý¿¡ ´ëÇؼ ¾Ë¾Æ º»´Ù.
jinja¶õ ÆÄÀ̽ã ÇÁ·Î±×·¡¹Ö ¾ð¾î¿ë À¥ ÅÛÇø´ ¿£ÁøÀÌ´Ù.
html¿¡¼ {}, {{}} ±ÔÄ¢À» ÀÌ¿ëÇØ °£´ÜÇÑ ÆÄÀ̽ã ÇÁ·Î±×·¡¹ÖÀÌ °¡´ÉÇÏ´Ù.
ÆÄÀ̽ãÀÇ º¯¼ö°¡ ³Ñ¾î ¿ÔÀ»¶§ Jinja2 ÅÛÇø´¿¡ ÀÇÇØ HTMLÀ» ²Ù¹Ð¼ö ÀÖ´Ù.
º¯¼ö
html¿¡¼ ÆÄÀ̽ãÀÇ º¯¼ö¸¦ »ç¿ë ÇÒ¼ö ÀÖ´Ù.
ÆÄÀ̽㠶ó¿ìÆà ÇÔ¼ö¿¡¼ jinja¿¡¼ »ç¿ëÇÒ º¯¼ö À̸§À» ³Ñ°Ü ÁØ´Ù.
html¿¡¼ ±âº» ¹®¹ý : {{ ÆÄÀ̽㠺¯¼ö À̸§ }} À¸·Î Ç¥Çö ÇÑ´Ù.
main.py ÆÄÀÏ
@app.route('/index/var')
def hello_name():
username = "john"
nickname = "king"
return render_template('variable.html', username=username, nickname=nickname)
main.html ÆÄÀÏ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Var Test</title>
</head>
<body>
<h3>Hello {{ username }}</h3>
<h3>{{ nickname }}</h3>
</body>
</html>
Á¦¾î¹® : IF
Á¶°ÇÀÌ °ÅÁþÀÎ °æ¿ì´Â µÎ°¡Áö´Ù.
1. º¯¼ö°¡ Á¤ÀÇ µÇ¾î ÀÖÁö ¾ÊÀº °æ¿ì, Çöó½ºÅ©¿¡¼ º¯¼ö°¡ ¾È³Ñ¾î ¿ÔÀ» ¶§ÀÌ´Ù.
2. ¼ýÀÚ°¡ 0À̰ųª ³í¸®°ªÀÌ falseÀÎ °æ¿ìÀÌ´Ù.
±âº» ¹®¹ý
{% if <Á¶°Ç> %}
<½ÇÇà HTML ÄÚµå>
{% elif <Á¶°Ç> %}
<½ÇÇà HTML ÄÚµå>
{% else %}
<½ÇÇà HTML ÄÚµå>
{% endif %}
main.py ÆÄÀÏ
from flask import Flask, render_template
app = Flask(__name__, template_folder="home_html")
@app.route("/index/hello")
def home():
stringValue = 'string value hello world'
return
render_template('hello.html', stringValue=stringValue)
return
render_template('hello.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8888, debug=True)
hello.html ÆÄÀÏ
<HTML>
<BODY>
{% if stringValue %}
<p>stringValue exists</p>
<p>{{stringValue}}</p>
{% else %}
<p>stringValue dose not exists</p>
{% endif %}
</BODY>
</HTML>
°á°ú)
stringValue exists
string value hello world
return render_template('hello.html') ¹®ÀÌ ½ÇÇàµÈ´Ù¸é, stringValue°¡ Á¤ÀǵǾî ÀÖÁö ¾Ê±â
¶§¹®¿¡ ½ÇÇà °á°ú´Â ´ÙÀ½°ú °°´Ù.
stringValue dose not exists
¹Ýº¹¹® : FOR
±âº» ¹®¹ý
{% for <º¯¼ö> in <¸®½ºÆ®> %}
<HTML ½ÇÇàÄÚµå>
{% endfor %}
main.py
from flask import Flask, render_template
app = Flask(__name__, template_folder="home_html")
@app.route("/index/hello")
def home():
user_list = ['john', 'chulsoo', 'kim']
return render_template('hello.html',
user_list=user_list)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8888, debug=True)
hello.html
<HTML>
<BODY>
{% if user_list %}
{% for user in user_list %}
<li>{{ user}}</li>
{% endfor %}
{% else %}
<p>user_list dose not exists</p>
{% endif %}
</BODY>
</HTML>
¶Ç´Â ´ÙÀ½°ú °°ÀÌ °£´ÜÇÏ°Ô Ç¥Çö ÇÒ¼öµµ ÀÖ´Ù.
hello.html
<HTML>
<BODY>
{% for user in user_list if user_list %}
<li>{{ user}}</li>
{% endfor %}
</BODY>
</HTML>
°á°ú)
Âü
Á¶)
Çöó½ºÅ©(Flask): Jinja2 ÅÛÇø´ ¿£Áö ±âº»¹®¹ý
http://192.168.219.103:8888/
|