Loading

Django(四)模板文件中的循环

编辑views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse  #此行增加
# Create your views here.
def plan(request):                   #此函数增加
    user=[]
    for i in range(20):
        user.append({'username':'jack'+str(i),'age':18+i})
    return render(request,'hello.html',{'hello':  user})

增加一个for循环,创建一个字典的列表。

把这个列表替换进模板

 

继续编辑模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
   {% for row in hello %}
        <h1>{{ row.username }}---{{ row.age }}</h1>
   {% endfor %}
</body>
</html>

body中的就是循环

有循环头部{% for row in hello %}

有循环尾部 {% endfor %}

 

注意其中我使用了hello      user       row   row.username  row.age

hello在render中,作为模板被替换的标志

hello在模板中,作为循环的列表。

user,在render中,作为替换内容,把hello这个特殊标记替换为user

user,在模板中,已经变成标记了,也就是hello

row,在for循环中,代表列表的一个条目,一行?

列表元素是字典,所以循环体中用row.username来标识列表中其中一个字典的索引。

row.age也一样。

 

你也可以试试下面的效果

   {% for row in hello %}
        <h1>{{ row}}</h1>
   {% endfor %}

 

 

像我这样不专业的业余选手,更喜欢用另一种方法,不用字典,用列表

row.0  row.1 row.2

也是可以用的参数。替换前,它是列表才行。

相关代码如下:

def plan(request):                   #此函数增加
    user=[]
    for i in range(20):
        temp = [18+i , '--',19+i]
        user.append(temp)
    return render(request,'hello.html',{'hello':  user})
   {% for row in hello %}
        <h1>{{ row.0}}</h1>
        <h3>{{ row.1 }}</h3>
        <h6>{{ row.2 }}</h6>
   {% endfor %}

 

posted @ 2017-12-23 19:29  上官飞鸿  阅读(1780)  评论(0编辑  收藏  举报