Django模板語言 Tags使用詳解
更新時間:2019年09月09日 08:49:25 作者:信奉上帝的小和尚
這篇文章主要介紹了Django模板語言 Tags使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
Tags
# 普通for循環(huán)
<ul>
{% for user in user_list %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
for循環(huán)可用的一些參數(shù):
| Variable | Description |
|---|---|
| forloop.counter | 當前循環(huán)的索引值(從1開始) |
| forloop.counter0 | 當前循環(huán)的索引值(從0開始) |
| forloop.revcounter | 當前循環(huán)的倒序索引值(從1開始) |
| forloop.revcounter0 | 當前循環(huán)的倒序索引值(從0開始) |
| forloop.first | 當前循環(huán)是不是第一次循環(huán)(布爾值) |
| forloop.last | 當前循環(huán)是不是最后一次循環(huán)(布爾值) |
| forloop.parentloop | 本層循環(huán)的外層循環(huán) |
for ... empty
# 如果user_list 里面元素為0個的時候執(zhí)行 empty
<ul>
{% for user in user_list %}
<li>{{ user.name }}</li>
{% empty %}
<li>空空如也</li>
{% endfor %}
</ul>
if判斷
# if,elif和else
{% if user_list %}
用戶人數(shù):{{ user_list|length }}
{% elif black_list %}
黑名單數(shù):{{ 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 total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
# 或
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
csrf_token
這個標簽用于跨站請求偽造保護。
在頁面的form表單里面寫上{% csrf_token %}
注意事項
Django的模板語言不支持連續(xù)判斷,即不支持以下寫法:
{% if a > b > c %}
...
{% endif %}
Django的模板語言中屬性的優(yōu)先級大于方法
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的值。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python遠程連接服務器MySQL數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了python遠程連接服務器MySQL數(shù)據(jù)庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07

