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

 

作者:上官飞鸿

出处:https://www.cnblogs.com/jackadam/p/8094195.html

版权:本作品采用「知识共享-署名-非商业性-禁止演绎(CC-BY-NC-ND)」许可协议进行许可。

posted @   上官飞鸿  阅读(1794)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示