官网:
中文版: 介绍-Jinja2中文文档
英文版: Template Designer Documentation — Jinja Documentation (2.11.x)
模板语法
1. 模板渲染
(1) app.py 准备数据
import jsonfrom flask import Flask,render_templateimport settingsapp = Flask(__name__)
app.config.from_object(settings) # 加载配置文件class Girl: # 自定义类def __init__(self, name):self.name = nameself.gender = "女"def __str__(self):return self.name@app.route("/show")
def show():name = "coco" # strage = 18 # intfirends = ["A", "B", "C"] # listdict1 = {"gift": "包"} # dict# 创建对象girlfriend = Girl("lili") # 自定义的类构建的类型: Girl类型# 向模板传递数据return render_template("index.html", name=name, age=age, firends=firends, dict1=dict1, girl=girlfriend)if __name__ == '__main__':app.run(port=8080)
(2) index.html 渲染数据
{{ name }}
{{ age }}
{{ firends.0 }} {#{{ list.0 }} 同 {{ list[0] }}#}
{{ dict1.gift }} {#{{ dict.key }} 同 {{dict.get(key) }}#}
{{ girl.name }} {#{{ gril.name }} 同 {{ 对象.属性 }}#}
2. if 判断 和 for 循环 和 loop 内置变量
(1)app.py 准备数据
from flask import Flask,render_templateimport settingsapp = Flask(__name__)
app.config.from_object(settings) # 加载配置文件@app.route("/show")
def show():girls = ["AA", "BBB", "CC"]dict1 = [{"name": "张三", "pwd": "123", "addr": "beijing", "phone": "13800000001"},{"name": "李四", "pwd": "123", "addr": "shanghai", "phone": "13800000002"},{"name": "王五", "pwd": "123", "addr": "guangzhou", "phone": "13800000003"},]return render_template("show.html", grils=girls, users=dict1)if __name__ == '__main__':app.run(port=8080)
(2) show.html渲染数据
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><style>.a {color: red;}</style>
</head>
<body><ul>
{#循环列表渲染数据#}{% for gril in grils %}<li>{{ gril }}</li>{% endfor %}
</ul>
<hr><ul>
{#循环列表,根据条件增加样式#}{% for gril in grils %}{% if gril|length>=3 %}<li class="a">{{ gril }}</li>{% else %}<li>{{ gril }}</li>{% endif %}{% endfor %}
</ul>
<hr><table border="1" cellpadding="0" cellspacing="0" width="50%">
{# 循环字典 #}{% for user in users %}<tr><td>{{ user.name }}</td><td>{{ user.pwd }}</td><td>{{ user.addr }}</td><td>{{ user.phone }}</td></tr>{% endfor %}
</table><hr><table border="1" cellpadding="0" cellspacing="0" width="50%">
{# 循环字典,根据条件增加样式 #}{% for user in users %}<tr {% if loop.index==2 %}style="background-color:aqua"{% endif %}><td>{{ loop.index }}</td><td>{{ user.name }}</td><td>{{ user.pwd }}</td><td>{{ user.addr }}</td><td>{{ user.phone }}</td></tr>{% endfor %}</table>
</body>
</html>