Django中template for如何使用方法
之前我們講過很多次for循環(huán)了,python中的循環(huán)有不少,不知道有沒有聽過template for這個(gè)循環(huán),這個(gè)也算是for循環(huán)的這一種延伸。
在for循環(huán)中還有很多有用的東西,如下:
變量 描述 forloop.counter 索引從 1 開始算 forloop.counter0 索引從 0 開始算 forloop.revcounter 索引從最大長(zhǎng)度到 1 forloop.revcounter0 索引從最大長(zhǎng)度到 0 forloop.first 當(dāng)遍歷的元素為第一項(xiàng)時(shí)為真 forloop.last 當(dāng)遍歷的元素為最后一項(xiàng)時(shí)為真 forloop.parentloop
用在嵌套的 for 循環(huán)中,
獲取上一層 for 循環(huán)的 forloop
也許有的小伙伴對(duì)template for的用法不是很明確,借著這個(gè)機(jī)會(huì),今天來講講新朋友template for循環(huán)。
當(dāng)列表為空或者非空時(shí)執(zhí)行不同操作:
{% for item in list %} ...{% empty %} ...{% endfor %}
使用forloop.counter訪問循環(huán)的次數(shù),下面這段代碼依次輸出循環(huán)的次數(shù),從1開始計(jì)數(shù):
{% for item in list %} ... {{ forloop.counter }} ...{% endfor %}
從0開始計(jì)數(shù):
{% for item in list %} ... {{ forloop.counter0 }} ...{% endfor %}
判斷是否是第一次循環(huán):
{% for item in list %} ... {% if forloop.first %} This is the first round. {% endif %} ...{% endfor %}
判斷是否是最后一次循環(huán):
{% for item in list %} ... {% if forloop.last %} This is the last round. {% endif %} ...{% endfor %}
逆向循環(huán):
{% for item in list reversed %} {{ item }}{% endfor %}
到此這篇關(guān)于Django中template for如何使用方法的文章就介紹到這了,更多相關(guān)Django template for內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP常用日期格式化函數(shù) FormatDate()2. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式3. PHP設(shè)計(jì)模式中工廠模式深入詳解4. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)5. XML入門的常見問題(二)6. 如何在jsp界面中插入圖片7. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法8. 利用CSS3新特性創(chuàng)建透明邊框三角9. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法10. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法
