DTL 模板 for

代码1:for in 循环:

遍历列表

views.py文件:
from django.shortcuts import render

def index(request):
context = {
“books”:[
“三国演义”,
“红楼梦”,
“水浒传”,
“西游记”
]
}
return render(request,‘index.html’,context=context)

index.html文件:

Title
    {% for book in books %}
  • {{ book }}
  • {% endfor %}

反向遍历index.html:

Title
    {% for book in books reversed %} ---使用reversed字段
  • {{ book }}
  • {% endfor %}

遍历字典:

views.py代码:
from django.shortcuts import render

def index(request):
context = {
“books”:[
“三国演义”,
“红楼梦”,
“水浒传”,
“西游记”
],
“person”:{
“username”:“张三”,
“age”:18,
“height”:180
}
}
return render(request,‘index.html’,context=context)
index.html代码:

Title
    {% for book in books reversed %}
  • {{ book }}
  • {% endfor %}
    {% for key in person.values %}
  • {{ key }}
  • {% endfor %}

index.html文件:

Title
    {% for book in books reversed %}
  • {{ book }}
  • {% endfor %}
    {% for key,values in person.items %} ----遍历字典的键值对。
  • {{ key }}/{{ values }}
  • {% endfor %}

遍历列表当中的字典:

index.html

Title
    {% for key,values in person.items %}
  • {{ key }}/{{ values }}
  • {% endfor %}
{% for book in books %} {% endfor %}
书名 作者 价格
{{ book.name }} {{ book.author }} {{ book.price }}

view.py:文件:

from django.shortcuts import render

def index(request):
context = {
“books”:[
{
“name”:“三国演义”,
“author”:“罗贯中”,
“price”:100
},
{
“name”:“水浒传”,
“author”:“施耐庵”,
“price”:120
},
{
“name”:“西游记”,
“author”:“吴承恩”,
“price”:130
},
{
“name”:“红楼梦”,
“author”:“曹雪芹”,
“price”:200
}
],
“person”:{
“username”:“张三”,
“age”:18,
“height”:180
}
}
return render(request,‘index.html’,context=context)

给遍历的标签添加背景效果:

Title
    {% for key,values in person.items %}
  • {{ key }}/{{ values }}
  • {% endfor %}
{% for book in books %} {% if forloop.first %} {% elif forloop.last %} {% else %} ------注意这里是开始的tr标签 {% endif %} {% endfor %}
序号 书名 作者 价格
{{ forloop.counter }} {{ book.name }} {{ book.author }} {{ book.price }}

for …in…empty代码:

views.py代码

from django.shortcuts import render

def index(request):
context = {
“books”:[
{
“name”:“三国演义”,
“author”:“罗贯中”,
“price”:100
},
{
“name”:“水浒传”,
“author”:“施耐庵”,
“price”:120
},
{
“name”:“西游记”,
“author”:“吴承恩”,
“price”:130
},
{
“name”:“红楼梦”,
“author”:“曹雪芹”,
“price”:200
}
],
“person”:{
“username”:“张三”,
“age”:18,
“height”:180
},
“comments”:[ ------文章的评论
“文章不错”,
“写的好”
]
}
return render(request,‘index.html’,context=context)

index.html代码:

Title
    {% for key,values in person.items %}
  • {{ key }}/{{ values }}
  • {% endfor %}
{% for book in books %} {% if forloop.first %} {% elif forloop.last %} {% else %} {% endif %} {% endfor %}
序号 书名 作者 价格
{{ forloop.counter }} {{ book.name }} {{ book.author }} {{ book.price }}
    {% for comment in comments %} -------演示遍历评论,有就打印,没有打印没有评论
  • {{ comment }}
  • {% empty %}
  • 没有任何评论
  • {% endfor %}

你可能感兴趣的:(Django)