django模板之自定義模板

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

QQ截圖20181203010349.png



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/

顯示:

QQ截圖20181203013207.png

相關文章
相關標籤/搜索