您的位置:首页 > 编程语言 > Go语言

django模板之自定义模板

2018-12-03 01:39 585 查看

使用环境:同上一篇django文章。



启动web服务:

cd py3/django-test1/test4

python manage.py runserver 192.168.255.70:8000


一、先演示在html模板中使用for标签循环:


编辑视图:

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模板:

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://19 5b4 2.168.255.70:8000/

显示:



二、演示在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>
    {%&nbs
38f8
p;endif %}
{% empty %}
<li>没找到任何符合是数据!</li>
{% endfor %}
</ul>

</body>
</html>

浏览器访问:http://192.168.255.70:8000/

显示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息