使用环境:同上一篇django文章。html
启动web服务:python
cd py3/django-test1/test4web
python manage.py runserver 192.168.255.70:8000django
1、先演示在html模板中使用for标签循环:vim
编辑视图:浏览器
vim bookshop/views.py from django.shortcuts import render from .models import * #查询一个值 #def index(request): # hero = HeroInfo.objects.get(pk=1) #查询主键(pk)=1的条目 # context = {'hero':hero} # return render(request,'bookshop/index.html',context) #查询多个值,在html模板中循环 def index(request): list = HeroInfo.objects.filter(isDelete=False) context = {'list1':list} return render(request,'bookshop/index.html',context)
编辑html模板:
ide
vim templates/bookshop/index.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> {{ hero.hname }}<br> {{hero.showname}} <hr> <ul> {% for hero in list1 %} <!--使用{{% for .. in ...%}}....{% endfor %}循环django传递过来的list1上下文对象,{{ forloop.counter }}是显示循环的第几回--> <li>{{forloop.counter }}: {{ hero.showname }}</li> <!-- #点号解析顺序:<br> #1.先把hero做为字典,showname为键查找<br> #2.再把hero做为对象,showname为属性或方法查找<br> #3.最后把hero做为列表,showname为索引查找<br> --> <!--{% empty %}是在视图函数中list = HeroInfo.objects.filter(isDelete=True)时,查询不存在的数据才显示的内容--> {% empty %} <li>没找到任何符合是数据!</li> {% endfor %} </ul> </body> </html>
浏览器访问:http://192.168.255.70:8000/ 函数
显示:oop
2、演示在html模板中使用if标签判断、注释、过滤器字体
仅修改html模板便可:
vim templates/bookshop/index.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> {# 这是单行注释 #} {% comment %} 这是 多行 注释 {% endcomment %} <ul> {% for hero in list1 %} <!--使用{% if %}判断,循环出的结果中,奇数行字体显示为蓝色,偶数行为红色--> {% if forloop.counter|divisibleby:"2" %} <!--除2运算使用过滤器(即|)--> <li style="color:red">{{forloop.counter }}: {{ hero.showname }}</li> {% else %} <li style="color:blue">{{forloop.counter }}: {{ hero.showname }}</li> {% endif %} {% empty %} <li>没找到任何符合是数据!</li> {% endfor %} </ul> </body> </html>
浏览器访问:http://192.168.255.70:8000/
显示: