温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django模板之自定义模板

发布时间:2020-06-29 18:12:47 来源:网络 阅读:342 作者:crystaleone 栏目:开发技术

使用环境:同上一篇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://192.168.255.70:8000/

显示:

django模板之自定义模板



二、演示在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/

显示:

django模板之自定义模板

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI