編輯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 %}
