一.Tags
(一)for
1.基本用法
<ul>
{% for user in user_list %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
2.for循環可用的一些參數
forloop.counter 當前循環的索引值(從1開始)
forloop.counter0 當前循環的索引值(從0開始)
forloop.revcounter 當前循環的倒序索引值(從1開始)
forloop.revcounter0 當前循環的倒序索引值(從0開始)
forloop.first 當前循環是不是第一次循環(布爾值)
forloop.last 當前循環是不是最后一次循環(布爾值)
forloop.parentloop 本層循環的外層循環
(二)for...empty
<ul>
{% for user in user_list %}
<li>{{ user.name }}</li>
{% empty %}
<li>空空如也</li>
{% endfor %}
</ul>
(三)if elif 和else
{% if user_list %}
用戶人數:{{ user_list|length }}
{% elif black_list %}
黑名單數:{{ black_list|length }}
{% else %}
沒有用戶
{% endif %}
(四)if ...else
{% if user_list|length > 5 %}
七座豪華SUV
{% else %}
黃包車
{% endif %}
if語句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。
(五)with
定義一個中間變量
{% with p_list.0.name as chenrun %}
{{chenrun}}
(六)csrf_token
這個標簽用于跨站請求偽造保護。
在頁面的form表單里面寫上{% csrf_token %}
(七)注意事項
1. Django的模板語言不支持連續判斷,即不支持以下寫法:
{% if a > b > c %}
...
{% endif %}
可以寫成 a>b and b>c
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的值。
二.母板
我們通常會在母板中定義頁面專用的CSS塊和JS塊,方便子頁面替換
(一).繼承母板
在子頁面中在頁面最上方使用下面的語法來繼承母板。
語法: {% extends 'layouts.html' %}
(二)塊(block)
通過在母板中使用{% block xxx %}來定義"塊"。
{% block page_panel %}
<h3 class="panel-title">出版社列表</h3>
{% endblock %}
在子頁面中通過定義母板中的block名來對應替換母板中相應的內容
{% block page_panel %}
<h3 class="panel-title">書名列表</h3>
{% endblock %}
三.組件
可以將常用的頁面內容如導航條,頁尾信息等組件保存在單獨的文件中,然后在需要使用的地方按如下語法導入即可。
{% include 'navbar.html' %}
四.靜態文件相關
(一)第一種方式static
1.導入
{% load static %}
2.使用
<script src="{% static "mytest.js" %}"></script>
注意:某個文件多處被用到可以存為一個變量
{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>
(二)第二種方式 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!" />
五.自定義simpletag
類似于自定義filter,只不過接收更靈活的參數
1.在app下創建templatetags
2.在templatetags下創建mydefination.py
3.注冊 simple tag
@register.simple_tag(name="plus")
def plus(a, b, c):
return "{} + {} + {}".format(a, b, c)
4.使用自定義simple tag
{% load mydefination %}
{% plus "1" "2" "abc" %}
六.inclusion_tag
多用于返回html代碼片段
1.在app下創建templatetags
2.在templatetags下創建mydefination.py
3.templatetags注冊 inclusion_tag
@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 {"data": data}
4.templates/result.html
<ul>
{% for choice in data %}
<li>{{ choice }}</li>
{% endfor %}
</ul>
5.templates/index.html
<body>
{% load my_inclusion %}
{% show_results 10 %}
</body>
轉載于:https://www.cnblogs.com/J-7-H-2-F-7/p/9630643.html