有时候我们前端的数据会随着后端的数据改变而改变,在前后端不分离的系统中,可通过jiajia2来实现模版渲染,这样前端也就更灵活。
1.{{ }}:实现动态模版加载
后端示例:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
projects = [
{"name": "项目1", "interface_num": 11, "time": "2022/3/17"},
{"name": "项目2", "interface_num": 22, "time": "2022/3/17"},
{"name": "项目3", "interface_num": 33, "time": "2022/3/17"},
{"name": "项目4", "interface_num": 44, "time": "2022/3/17"},
]
# render_template()中第1个参数后面的参数,会将数据传给第1个参数页面,页面中若存在{{ }},则会匹配后面参数的数据。
return render_template('index.html', pro=projects, title='测试平台')
if __name__ == '__main__':
app.run(debug=True)
前端示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<div>
{{ pro }}
</div>
</body>
</html>
效果:
2.使用jinjia中的for循环,美化格式
{% for p in projects %}
项目:{{ p.name }} : {{ p.interfaces }}
{% endfor %}
后端代码不变:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
projects = [
{"name": "项目1", "interface_num": 11, "time": "2022/3/17"},
{"name": "项目2", "interface_num": 22, "time": "2022/3/17"},
{"name": "项目3", "interface_num": 33, "time": "2022/3/17"},
{"name": "项目4", "interface_num": 44, "time": "2022/3/17"},
]
# render_template()中第1个参数后面的参数,会将数据传给第1个参数页面,页面中若存在{{ }},则会匹配后面参数的数据。
return render_template('index.html', pro=projects, title='测试平台')
if __name__ == '__main__':
app.run(debug=True)
前端代码修改:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for project in pro %}
<div>项目名称:{{ project["name"] }},接口数量:{{ project["interface_num"] }},创建日期:{{ project["time"] }}</div>
{% endfor %}
</body>
</html>
效果:
for循环排序:获取循环中的index: {{ loop.index }}
loop.index: 当前循环迭代的次数,从1开始
loop.index0: 当前循环迭代的次数,从0开始
loop.revindex: 当前循环的逆序次数,从最后一个index开始,直到1
loop.revindex0: 当前循环的逆序次数,从最后一个index开始,直到0
loop.first: 如果是第一次循环迭代,为True
loop.last: 如果是最后一次循环迭代,为True
loop.length: 序列中的项目数(长度)
前端修改:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for project in pro %}
<div>序号:{{ loop.index }}--项目名称:{{ project["name"] }},接口数量:{{ project["interface_num"] }},创建日期:{{ project["time"] }}</div>
{% endfor %}
</body>
</html>
效果:
loop判断:
{% if loop.last %}
xxxxxx
{% else %}
xxxxxx
{% endif %}
前端代码修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for project in pro %}
{% set name=project.name %} <!--# 设置变量-->
{% if not loop.last %}
<div>序号:{{ loop.nextitem.name }}--项目名称:{{ name }},接口数量:{{ project["interface_num"] }},创建日期:{{ project["time"] }}</div>
{% else %}
<div>序号:{{ loop.index }}--项目名称:{{ name }},接口数量:{{ project["interface_num"] }},创建日期:{{ project["time"] }}</div>
{% endif %}
{% endfor %}
</body>
</html>