有关django之template渲染及html内循环

结构如下:

mysite-
|
|--monitor
|    |
|    |--views
|       |--urls
|--mysite(默认创建)
|    |
|    |--settings
|       |--urls
|--templates
|      |
|      |--monitor
|          |--kkk.html

urls内容

from django.urls import path
from monitor import views
urlpatterns = [
    path('kkk/',views.kkk),
]

monitor.views内容

from django.shortcuts import render
def kkk(request):
    c=[ {'name':'KK', 'age':221},
        {'name':'KK2','age': 222},
        {'name':'KK3','age': 223},
        {'name':'KK4','age': 224},
        {'name':'KK5','age': 225}]
    return render(request,'monitor/kkk.html',{'bit':c})

kkk.html文件内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>kkk</title>
</head>
<body>
<ul>
    {% for usa in bit %}    
    {% if forloop.counter|divisibleby:2  %}    ##此处用来判断是偶数还是奇数,如果是偶数行修改红色,奇数修改为蓝色
        <li style="color: red">uname:{{usa.name}},uage:{{usa.age}}</li>
    {% else %}
        <li style="color: blue;">uname:{{usa.name}},uage:{{usa.age}}</li>
    {% endif %}
    {% endfor %}
</ul>
</body>
</html>

访问127.0.0.1:8000/kkk 验证

 

posted on 2018-06-06 16:32  世马  阅读(207)  评论(0编辑  收藏  举报