Jinja2
樣板引擎可以處裡 .html
檔在 Jinja2
除了可以解析 HTML
語法,還有兩種特殊的標籤:{{ }}
跟 {% %}
。{{ }}
上一篇講過是使用在渲染到頁面上的標籤,而 {% %}
則是是使用在各種判斷以及迴圈使用的標籤。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
</head>
<body>
<div>
{% if username %}
<h1>Welcome {{ username }}</h1>
{% else %}
<h1>Hello</h1>
{% endif %}
</div>
</body>
</html>
app.py
import configs as CONFIGS
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object(CONFIGS)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/<name>")
def index_name(name):
return render_template('index.html', username=name)
if __name__ == "__main__":
app.run()
執行結果
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
</head>
<body>
<div>
{% for username in users %}
<h1>Welcome {{ username }}</h1>
{% endfor %}
</div>
</body>
</html>
app.py
import configs as CONFIGS
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object(CONFIGS)
@app.route('/<int:time>')
def index_time(time):
users = []
for i in range(time):
users = users + [f'user {i}']
return render_template('index.html', users=users)
執行結果