zoukankan      html  css  js  c++  java
  • 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.zhihu.com/question/20842791
    asp.net cookie and session
    leelazero and google colab
    download file by python in google colab
    physical processor, core, logical processor
    通过powershell操作eventlog
    openxml in sql server
    get the page name from url
    How to Execute Page_Load() in Page's Base Class?
    Difference between HttpContext.Request and Request
  • 原文地址:https://www.cnblogs.com/jackadam/p/8094195.html
Copyright © 2011-2022 走看看