列表中套字典,在HTML中读取

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样式,最后输出(这是我数据库的输出):

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值