只需要記兩種特殊符號:
變量相關的用{{}},
邏輯相關的用{%%}。
一、變量
當模版系統遇到點("."),它將以這樣的順序查詢:
字典查詢(Dictionary lookup)
屬性或方法查詢(Attribute or method lookup)
數字索引查詢(Numeric index lookup)
注意事項:
- 如果計算結果的值是可調用的,它將被無參數的調用。 調用的結果將成為模版的值。
- 如果使用的變量不存在, 模版系統將插入 string_if_invalid 選項的值, 它被默認設置為'' (空字符串) 。
def template_test(request): l = [11, 22, 33] d = {"name": "alex"} class Person(object): def __init__(self, name, age): self.name = name self.age = age def dream(self): return "{} is dream...".format(self.name) Alex = Person(name="Alex", age=34) Egon = Person(name="Egon", age=9000) Eva_J = Person(name="Eva_J", age=18) person_list = [Alex, Egon, Eva_J] return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list})
{% 取l中的第一個參數 %}
{{ l.0 }}
{% 取字典中key的值 %}
{{ d.name }}
{% 取對象的name屬性 %}
{{ person_list.0.name }}
{% .操作只能調用不帶參數的方法 %}
{{ person_list.0.dream }}
二、Filters(過濾器)
在Django的模板語言中,通過使用 過濾器 來改變變量的顯示。
過濾器的語法: {{ value|filter_name:參數 }}
使用管道符"|"來應用過濾器。
例如:{{ name|lower }}會將name變量應用lower過濾器之后再顯示它的值。lower在這里的作用是將文本全都變成小寫。
注意事項:
- 過濾器 支持“鏈式”操作。即一個過濾器的輸出作為另一個過濾器的輸入。
- 過濾器 可以接受參數,例如:{{ sss|truncatewords:30 }},這將顯示sss的前30個詞。
- 過濾器 參數包含空格的話,必須用引號包裹起來。比如使用逗號和空格去連接一個列表中的元素,如:{{ list|join:', ' }}
- '|'左右 沒有空格沒有空格沒有空格
2.1 內置過濾器
#如果一個變量是false或者為空,使用給定的默認值。 否則,使用變量的值。 {{ value|default:"nothing"}} #返回值的長度,作用於字符串和列表。 {{ value|length }} #將值格式化為一個 “人類可讀的” 文件尺寸 {{ value|filesizeformat }} #切片 {{value|slice:"2:-1"}} #時間格式化 {{ value|date:"Y-m-d H:i:s"}} #告訴Django這段代碼是安全的不必轉義【xss攻擊】 {{ value|safe}} #截斷超出的字符串,將以可翻譯的省略號序列(“...”)結尾 {{ value|truncatechars:9}} #移除 value中所有的與給出的變量相同的字符串 {{ value|cut:' ' }} #使用字符串連接列表 {{ value|str.join(list)}} #將日期格式設為自該日期起的時間, {{ blog_date|timesince:comment_date }} #測量從現在開始直到給定日期或日期時間的時間 例如,如果今天是2006年6月1日,而conference_date是保留2006年6月29日的日期實例,則{{ conference_date | timeuntil }}將返回“4周”。 {{ conference_date|timeuntil:from_date }}
2.2 自定義filter
自定義過濾器只是帶有一個或兩個參數的Python函數:
- 變量(輸入)的值 - -不一定是一個字符串
- 參數的值 - 這可以有一個默認值,或完全省略
#自定義filter代碼文件擺放位置: app01/ __init__.py models.py templatetags/ # 在app01下面新建一個package package __init__.py app01_filters.py # 建一個存放自定義filter的文件 views.py
# 編寫自定義filter from django import template register = template.Library() @register.filter(name="cut") def cut(value, arg): return value.replace(arg, "") @register.filter(name="addSB") def add_sb(value): return "{} SB".format(value)
#模板語言中,使用自定義filter {# 先導入我們自定義filter那個文件 #} {% load app01_filters %} {# 使用我們自定義的filter #} {{ somevariable|cut:"0" }} {{ d.name|addSB }}
2.3 自定義simple_tag
#和自定義filter類似,只不過接收更靈活的參數。 #定義注冊simple tag @register.simple_tag(name="plus") def plus(a, b, c): return "{} + {} + {}".format(a, b, c) #使用自定義simple tag {% load app01_simple_tag %} {% plus "1" "2" "abc" %}
2.4 自定義inclusion_tag
多用於返回html代碼片段
①templatetags/my_inclusion.py
from django import template register = template.Library() @register.inclusion_tag('result.html') def show_results(n): n = 1 if n < 1 else int(n) data = ["第{}項".format(i) for i in range(1, n+1)] return {"reg": data}
②templates/result.html
<ul> {% for choice in reg %} <li>{{ choice }}</li> {% endfor %} </ul>
③templates/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>inclusion_tag test</title> </head> <body> {% load inclusion_tag_test %} {% show_results 10 %} </body> </html>
三、Tags
1、for循環
#普通for循環 <ul> {% for user in user_list %} <li>{{ user.name }}</li> {% endfor %} </ul> # for ... empty <ul> {% for user in user_list %} <li>{{ user.name }}</li> {% empty %} <li>空空如也</li> {% endfor %} </ul>
| Variable | Description |
|---|---|
forloop.counter |
當前循環的索引值(從1開始) |
forloop.counter0 |
當前循環的索引值(從0開始) |
forloop.revcounter |
當前循環的倒序索引值(從1開始) |
forloop.revcounter0 |
當前循環的倒序索引值(從0開始) |
forloop.first |
當前循環是不是第一次循環(布爾值) |
forloop.last |
當前循環是不是最后一次循環(布爾值) |
forloop.parentloop |
本層循環的外層循環 |
2、if判斷
if語句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。
{% if user_list %}
用戶人數:{{ user_list|length }}
{% elif black_list %}
黑名單數:{{ black_list|length }}
{% else %}
沒有用戶
{% endif %}
3、with
定義一個中間變量,多用於給一個復雜的變量起別名。
注意等號左右不要加空格。
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
或
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
4、csrf_token
這個標簽用於跨站請求偽造保護。
在頁面的form表單里面寫上{% csrf_token %}
5、注釋
{# ... #}
6、注意事項
(1)Django的模板語言不支持連續判斷,即不支持以下寫法:
{% if a > b > c %}
...
{% endif %}
(2) Django的模板語言中屬性的優先級大於方法
def xx(request):
d = {"a": 1, "b": 2, "c": 3, "items": "100"}
return render(request, "xx.html", {"data": d})
如上,我們在使用render方法渲染一個頁面的時候,傳的字典d有一個key是items並且還有默認的 d.items() 方法,此時在模板語言中:
{{ data.items }}
默認會取d的items key的值。
四、母版
①什么時候用母版?
html頁面有重復的代碼,把它們提取出來放到一個單獨的html文件。(比如:導航條和左側菜單)
② 子頁面如何使用母版?
{% extends 'base.html' %} --> 必須要放在子頁面的第一行
母版里面定義block(塊),子頁面使用block(塊)去替換母版中同名的塊
1、母版
通常會在母板中定義頁面專用的CSS塊和JS塊,方便子頁面替換。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> {% block page-css %} {% endblock %} </head> <body> <h1>這是母板的標題</h1> {% block page-main %} {% endblock %} <h1>母板底部內容</h1> {% block page-js %} {% endblock %} </body> </html>
2、繼承母版
在子頁面中在頁面最上方使用下面的語法來繼承母板。
{# 繼承母版 #} {% extends 'base.html' %} {# 把自己頁面的內容 塞到母版里面相應的位置 #} {% block page-main %} <h1 class="page-header">書籍管理頁面</h1> <div class="panel panel-primary"> <!-- Default panel contents --> <div class="panel-heading">書籍列表 <i class="fa fa-thumb-tack pull-right"></i></div> <div class="panel-body"> <div class="row" style="margin-bottom: 15px"> <div class="col-md-4"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-btn"> <button class="btn btn-default" type="button">搜索</button> </span> </div><!-- /input-group --> </div><!-- /.col-md-4 --> <div class="col-md-3 pull-right"> <a href="/add_book/" class="btn btn-success pull-right">新頁面添加</a> <button class="btn btn-success pull-right" data-toggle="modal" data-target="#myModal">新增</button> </div> </div><!-- /.row --> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>id</th> <th>書名</th> <th>出版社名稱</th> <th>操作</th> </tr> </thead> <tbody> {% for i in all_book %} <tr> <td>{{ forloop.counter }}</td> <td>{{ i.id }}</td> <td>{{ i.title }}</td> <td>{{ i.publisher.name }}</td> <td> <a class="btn btn-danger" href="/delete_book/?id={{ i.id }}">刪除</a> <a class="btn btn-info" href="/edit_book/?id={{ i.id }}">編輯</a> </td> </tr> {% empty %} <tr> <td colspan="5" class="text-center">暫時沒有數據哦~</td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation" class="text-right"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> </div> {% endblock %}
3、塊
通過在母板中使用{% block xxx %}來定義"塊"。
在子頁面中通過定義母板中的block名來對應替換母板中相應的內容。
{% block page-js %} <script src="/static/author_list_only.js"></script> {% block page-css %} {% load static %} {# <link rel="stylesheet" href="{% static 'book_list_only.css' %}">#} <link rel="stylesheet" href="{% get_static_prefix %}book_list_only.css"> {% endblock %}
4、靜態文件相關
(1){% static %}
{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />
引用JS文件時使用:
{% load static %}
<script src="{% static "mytest.js" %}"></script>
某個文件多處被用到可以存為一個變量
{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>
(2){% get_static_prefix %}
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />
或者
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!" />
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!" />
5、組件
可以將常用的頁面內容如導航條,頁尾信息等組件保存在單獨的文件中,然后在需要使用的地方按如下語法導入即可。
{% include 'navbar.html' %}
