django模板之自定義模板

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

顯示:

QQ截圖20181203010349.png



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

顯示:

QQ截圖20181203013207.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章