標(biāo)簽
1、for標(biāo)簽
<h3>循環(huán)取值1</h3><hr>
{% for item in person_list %}
<p>{{ item.name }},{{ item.age }}</p>
{% endfor %}
<h3>循環(huán)取值2:倒序</h3><hr>
{% for item in person_list reversed %}
<!--序號從1開始-->
<p>{{ forloop.counter }}----->{{ item.name }},{{ item.age }}</p>
<!--序號從0開始--><p>{{ forloop.counter0 }}----->{{ item.name }},{{ item.age }}</p><!-- 序號倒序 --><p>{{ forloop.revcounter }}----->{{ item.name }},{{ item.age }}</p>
{% endfor %}
<h3>循環(huán)取值3:字典</h3><hr>
{% for k,v in d.items %}
<p>{{ k }},{{ v}}</p>
{% endfor %}
注:循環(huán)序號快運(yùn)通過forloop
顯示
2键畴、for....empty:當(dāng)給出的組為空或沒有被找到時盈罐,可以有所操作
{% for person in person_list %}
<p>{{ person.name }}</p>
{% empty %}
<p>sorry,no person here</p>
{% endfor %}
3、if標(biāo)簽:對一個給出的變量進(jìn)行判斷损搬,如果為True
(存在碧库,不為空,且不是boolean類型的false值)巧勤,對應(yīng)的內(nèi)容會顯示
{% if i > 300 %}
<p>大于{{ i }}</p>
{% elif i == 200 %}
<p>等于{{ i }}</p>
{% else %}
<p>小于{{ i }}</p>
{% endif %}
4嵌灰、with標(biāo)簽:使用一個簡單的名字緩存一個復(fù)雜的變量,當(dāng)你需要使用一個昂貴的方法(訪問數(shù)據(jù)庫)很多次的時候是非常有用的
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
<p>{{ person_list.2.name }}</p>
{% with name=person_list.2.name %}
<p>{{ name }}</p>
{% endwith %}
5颅悉、csrf_token標(biāo)簽:用于跨站請求偽造保護(hù)
在form表單下面添加一個{% csrf_token %}
<h3>scrf_token</h3><form action="/tag/" method="post">
{% csrf_token %}
<p><input type="text" name="haiyan"></p>
<input type="submit">
</form>