python中的列表套字典,作为参数传到html中,再读取字典中的数据,最后输出,逻辑就是这样。
这里使用的的字典命名为rank_data,列表是rank_list。
传列表时,一定要看清传的参数名是否正确,我就是因为传成了字典名,然后输出的时候一直输出不了,整的我都怀疑是不是html不能识别列表里面套字典的数据,结果最后一看数据传错了。
def index(request):
# 定义一个空列表
data_list = []
# 使用for循环,从数据库中读取到字典内容,这里假设读到了一个字典:
rank_data = {
"id": 1, # 序号
"name": liuxp, # 姓名
"num": 99, # 参加比赛次数
"total_score": 365, # 总积分
}
# 将字典加到列表中
rank_list.append(rank_data)
# 将列表data_list传入html
retrun render(request, "index.html",
{'rank_list': rank_list})
在index.html接收到列表后,使用for循环取得数据:
{% load static %}
<!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>登录</title>
<link rel="stylesheet" href={% static '/plugins/bootstrap- 3.4.1/css/bootstrap.css' %}>
</head>
<body>
<div class="container">
<div class="panel panel-info" style="height: 500px;">
<!-- Default panel contents -->
<div class="panel-heading">输出</div>
<!-- Table -->
<table class="table table-striped" >
<thead>
<tr>
<th>排名</th>
<th>昵称</th>
<th>参加考试次数</th>
<th>总积分</th>
</tr>
</thead>
<tbody>
{% for item in rank_list%}
<tr>
<th scope="row">{% if item %}{{ item.id }}{% else %}暂无{% endif %}</th>
<td>{% if item %}{{ item.name }}{% else %}暂无{% endif %}</td>
<td>{% if item %}{{ item.num }}{% else %}暂无{% endif %}</td>
<td>{% if item %}{{ item.total_score }}{% else %}暂无{% endif %}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</body>
其中的主要代码,其实就一行,通过for循环和这行代码来读取列表中的字典数据:
{{ item.键名 }}
再结合bootstrap样式,最后输出(这是我数据库的输出):