1. 程式人生 > >Python-Django 模板層

Python-Django 模板層

1 模版簡介

DTL:django模板語言
核心:
變數 {{ }}
標籤 {% %}

2 模版語法之變數

-變數渲染:{{變數}}
-變數深度查詢:{{變數.索引/key值/方法}}

 

<h2>當前時間戳</h2>
@@[email protected]@
{{ ctime }}
<h1>變數</h1>
<p>{{ age }}</p>
<p>{{ name }}</p>
<p>{{ dic }}</p>
<p>{{ li }}</p>
<h2>取出字典的名字</h2>
<p>{{ dic.name }}</p>
<h2>取出列表中的某個值</h2>
<p>{{ li.0 }}</p>
<h2>變數之物件</h2>
<p>{{ lqz }}</p>
<p>{{ lqz.test1 }}</p>
<h2>類呼叫方法不行,智慧用物件</h2>
<p>{{ Test.test2 }}</p>
<p>{{ lqz.test2 }}</p>
def test(request):
    # 顯示時間戳
    # with open('templates/test01.html','r') as f:
    #     data=f.read()
    # data=data.replace('@@[email protected]@',str(time.time()))
    # return HttpResponse(data)
    # ctime=str(time.time())
    # return render(request, 'test01.html', {'ctime': ctime})
    # 變數
    age=17
    name='dhhfg'
    dic={'name':'紅樓','pub_date':'2018-12-30','price':888}
    li=['dgfgf',18]
    li2=[]
    # locals()把所有區域性變數傳到模板中
    class Test():
        def __init__(self, name, pwd):
            self.name = name
            self.pwd = pwd
        def test1(self):
            return self.name
        def __str__(self):
            return self.pwd
        @classmethod
        def test2(cls):
            return 'clsss'

    lqz = Test('lqz', '123')
    # print(lqz)
    # print(lqz.test1())

    file_size=10240000
    bol=[]
    import _datetime
    today=_datetime.datetime.now()
    h1='hello world abc'
    href='<a href="http://www.baidu.com">baidu</a>'
    from django.utils.safestring import mark_safe
    href2=mark_safe(href)
    return render(request,'test01.html',locals())

  

3 模版之過濾器

變數之過濾器(是個函式)
-語法:(後面只能傳一個引數)
{{變數名|過濾器的名字:引數}}
-內建過濾器:
<p>{{ age|add:3 }}</p>
<p>{{ name|length }}</p>
<p>{{ bol|default:'123' }}</p>
<p>{{ ll2|default:'我是空的' }}</p>
<p>{{ file_size|filesizeformat }}</p>
<p>{{ ctime }}</p>
<p>{{ ctime|date:'Y年m月' }}</p>
<p>{{ name|slice:'2:4' }}</p>
<p>{{ name|truncatechars:6 }}</p>
<p>{{ name2|truncatewords:2}}</p>
<p>{{ href|safe }}</p>

 

<h1>過濾器</h1>
<p>age+100</p>
<p>{{ age|add:100 }}</p>
<p>name lenght</p>
<p>{{ name|length }}</p>
<p>bol default</p>
<p>{{ bol|default:'123' }}</p>
<h2>filesize </h2>
<p>{{ file_size|filesizeformat }}</p>
<h2>date</h2>
<p>{{ today|date:'Y年m月d日' }}</p>
<h2>slice</h2>
<p>{{ h1|slice:':-1' }}</p>
<p>{{ h1|slice:'0:2' }}</p>
<p>{{ h1|slice:'-5:-1' }}</p>
<h2>truncatehars</h2>
<p>{{ h1|truncatechars:6 }}</p>
<h2>truncatewords</h2>
<p>{{ h1|truncatewords:2 }}</p>
<h2>href</h2>
<p>{{ href|safe }}</p>
<p>{{ href2 }}</p>

4 模版之標籤

-語法:{% %}
-foo是一個可迭代物件
{% for a in foo %}

{% endfor %}
-forloop:counter,couter0,revcounter,revcouter0,first,last,parentloop:父迴圈的forloop物件
-for--empty的使用
{% for foo in ll2 %}
{{ foo }}
{% empty %}
沒有值啊
{% endfor %}
-if判斷
{% if ll2 %}
ll2 有值
{% elif ll %}
ll有值
{% else %}
ll2 沒有值
{% endif %}
-with重新命名
{% with dic.hobby.1 as a %}
{#{% with a=dic.hobby.1 %}#}
{{ a }}
<p>aaaa</p>
{{ a }}

{% endwith %}

 

<h1>模板之標籤</h1>
<h2>for</h2>
{% for foo in li %}
<p>{{ foo }}</p>
{% endfor %}
<h2>li2------</h2>
{% for foo in li2 %}
<p>{{ foo }}</p>
{% empty %}
<p>no,data</p>
{% endfor %}
<h2>if</h2>
{% if li %}
data
{% elif age > 10 %}
age>10
{% else %}
age<10
{% endif %}
<h2>with</h2>
{#{% with li.1 as a %}#}
{% with a=li.0 %}
{{ a }}
{% endwith %}

5 自定義過濾器

1 確認app是否在settings中註冊
2 在app下建立templatetags的模組(名字固定)
3 在模組下建立py檔案(名字隨意)--->在模板中{% load py檔名字%}
4 在py檔案中寫過濾器
from django.template import Library
register = Library()
#指定了name之後,模板上使用的時候,直接用name呼叫,如果沒指定name,就用函式的名字
# 過濾器最多有兩個引數
@register.filter(name='myadd')
def my_add(a,b):
print(a+b)
return a+b
5 模板中使用
-1 {% load py檔名字%}
-2 {{ 變數|myadd:1}}

 

from django.template import Library
from app01.models import *

register = Library()
#指定了name之後,模板上使用的時候,直接用name呼叫,如果沒指定name,就用函式的名字
# 過濾器最多有兩個引數
@register.filter(name='myadd')
def my_add(a,b):
print(a+b)
return a+b

{% load my_tag %}
{{ age|myadd:4 }}
{% if age|myadd:4 > 20 %}
大於20
{% endif %}
# -寫一個過濾器:
# -實現過濾敏感詞彙
# 操--->和諧
# 你麻痺--->民主
# -替換的字元,是可以配置的
@register.filter(name='senword')
def sen_word(word):
sen_word=Sen.objects.filter(sen=word)
if sen_word:
return sen_word[0].cha
return word

{% for i in content %}
{% load my_tag %}
<p>{{ i.data|senword }}</p>
{% endfor %}


6 自定義標籤

1 確認app是否在settings中註冊
2 在app下建立templatetags的模組(名字固定)
3 在模組下建立py檔案(名字隨意)--->在模板中{% load py檔名字%}
4 在py檔案中寫過濾器
from django.template import Library
register = Library()
#指定了name之後,模板上使用的時候,直接用name呼叫,如果沒指定name,就用函式的名字
# 過濾器最多有兩個引數
@register.simple_tag(name='mytag')
def my_tag(a,b,c):
return a+b+c
5 模板中使用
-1 {% load py檔名字%}
-2 {% mytag 引數1 引數2 引數3%}

 

# 自定義一個標籤
# 標籤可以傳多個引數
@register.simple_tag(name='mytag')
def my_tag(a,b,c):
return a+b+c

{#標籤不能跟在if判斷後面#}
{#{% if mytag 1 2 3 > 30 %}#}
{# #}
{#{% endif %}#}
{% mytag 1 2 3 %}

7 標籤和過濾器的區別:

1 標籤可以傳多個引數,過濾器最多隻能傳2個
2 使用過濾器{{ }} 標籤使用:{% %}
3 ****重點:過濾器可以放在if判斷後,標籤不能放在if判斷後