Django学习手册

先在views视图内,定义列表数据,以及字典数据。运用render函数传递两个列表数据至前端。

from django.shortcuts import render

list_info = [
    {"name":"root1","phone":"111"},
    {"name":"root2","phone":"222"},
    {"name":"root3","phone":"333"},
    {"name":"root4","phone":"444"},
    {"name":"root5","phone":"555"},
    {"name":"root6","phone":"666"},
    {"name":"root7","phone":"777"},
]
dict_info = {
    "1":{"name":"root1","phone":"111"},
    "2":{"name":"root2","phone":"222"},
    "3":{"name":"root3","phone":"333"},
    "4":{"name":"root4","phone":"444"},
    "5":{"name":"root5","phone":"555"},
    "6":{"name":"root6","phone":"666"},
    "7":{"name":"root7","phone":"777"},
}

def index(request):
    return render(request,"index.html",{"list_info":list_info,"dict_info":dict_info})

配置URL:

前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <ul>列表循环:列表【字典】
        {% for i in list_info %}
             <li>
                {{ i }}
                 <br>
                {{ i.name }}
                <br>
            </li>
        {% endfor %}
    </ul>

    <ur>字典循环:
        {% for i in dict_info %}
            <li>
                {{ i }}
            </li>
        {% endfor %}
    </ur>

    <ur>字典循环:(keys)
        {% for i in dict_info.keys %}
            <li>
                {{ i }}
            </li>
        {% endfor %}
    </ur>

    <ur>字典循环:(values)
        {% for i in dict_info.values %}
            <li>
                {{ i }}
            </li>
        {% endfor %}
    </ur>

    <ur>字典循环:(items)
        {% for i,j in dict_info.items %}
            <li>
                {{ i }} --- {{ j }} --- {{ j.name }} ---{{ j.phone }}
            </li>
        {% endfor %}
    </ur>
</div>
<script src="/static/jquery.js"></script>
</body>
</html>
原文地址:https://www.cnblogs.com/Anec/p/9552625.html