欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django模板語言 Tags使用詳解

 更新時(shí)間:2019年09月09日 08:49:25   作者:信奉上帝的小和尚  
這篇文章主要介紹了Django模板語言 Tags使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

Tags

# 普通for循環(huán)

<ul>
{% for user in user_list %}
  <li>{{ user.name }}</li>
{% endfor %}
</ul>

for循環(huán)可用的一些參數(shù):

Variable Description
forloop.counter 當(dāng)前循環(huán)的索引值(從1開始)
forloop.counter0 當(dāng)前循環(huán)的索引值(從0開始)
forloop.revcounter 當(dāng)前循環(huán)的倒序索引值(從1開始)
forloop.revcounter0 當(dāng)前循環(huán)的倒序索引值(從0開始)
forloop.first 當(dāng)前循環(huán)是不是第一次循環(huán)(布爾值)
forloop.last 當(dāng)前循環(huán)是不是最后一次循環(huán)(布爾值)
forloop.parentloop 本層循環(huán)的外層循環(huán)

for ... empty

# 如果user_list 里面元素為0個(gè)的時(shí)候執(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 %}
# 當(dāng)然也可以只有if和else

{% if user_list|length > 5 %}
 七座豪華SUV
{% else %}
  黃包車
{% endif %}

# if語句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。

with

# 定義一個(gè)中間變量,多用于給一個(gè)復(fù)雜的變量起別名。

# 注意等號(hào)左右不要加空格。

{% with total=business.employees.count %}
  {{ total }} employee{{ total|pluralize }}
{% endwith %}

# 或

{% with business.employees.count as total %}
  {{ total }} employee{{ total|pluralize }}
{% endwith %}

csrf_token

這個(gè)標(biāo)簽用于跨站請(qǐng)求偽造保護(hù)。

在頁面的form表單里面寫上{% csrf_token %}

注意事項(xiàng)

Django的模板語言不支持連續(xù)判斷,即不支持以下寫法:

{% if a > b > c %}
...
{% endif %}

Django的模板語言中屬性的優(yōu)先級(jí)大于方法

def xx(request):
  d = {"a": 1, "b": 2, "c": 3, "items": "100"}
  return render(request, "xx.html", {"data": d})

如上,我們?cè)谑褂胷ender方法渲染一個(gè)頁面的時(shí)候,傳的字典d有一個(gè)key是items并且還有默認(rèn)的 d.items() 方法,此時(shí)在模板語言中:

{{ data.items }}

默認(rèn)會(huì)取d的items key的值。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論