views.py文件:
from django.shortcuts import render
def index(request):
context = {
“books”:[
“三国演义”,
“红楼梦”,
“水浒传”,
“西游记”
]
}
return render(request,‘index.html’,context=context)
index.html文件:
Title
反向遍历index.html:
Title
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代码:
{% for key in person.values %}
- {{ key }}
{% endfor %}
index.html文件:
Title
{% for key,values in person.items %} ----遍历字典的键值对。
- {{ key }}/{{ values }}
{% endfor %}
书名
作者
价格
{% for book in books %}
{{ book.name }}
{{ book.author }}
{{ book.price }}
{% endfor %}
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)
序号
书名
作者
价格
{% for book in books %}
{% if forloop.first %}
{% elif forloop.last %}
{% else %}
------注意这里是开始的tr标签
{% endif %}
{{ forloop.counter }}
{{ book.name }}
{{ book.author }}
{{ book.price }}
{% endfor %}
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)
序号
书名
作者
价格
{% for book in books %}
{% if forloop.first %}
{% elif forloop.last %}
{% else %}
{% endif %}
{{ forloop.counter }}
{{ book.name }}
{{ book.author }}
{{ book.price }}
{% endfor %}
{% for comment in comments %} -------演示遍历评论,有就打印,没有打印没有评论
- {{ comment }}
{% empty %}
- 没有任何评论
{% endfor %}