国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python的Django框架中if標簽的相關使用

2020-01-04 18:04:03
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了Python的Django框架中if標簽的相關使用,是Django框架使用中的基礎知識,需要的朋友可以參考下

{% if %} 標簽檢查(evaluate)一個變量,如果這個變量為真(即,變量存在,非空,不是布爾值假),系統會顯示在 {% if %} 和 {% endif %} 之間的任何內容,例如:

 

 
  1. {% if today_is_weekend %} 
  2. <p>Welcome to the weekend!</p> 
  3. {% endif %} 

{% else %} 標簽是可選的:

 

 
  1. {% if today_is_weekend %} 
  2. <p>Welcome to the weekend!</p> 
  3. {% else %} 
  4. <p>Get back to work.</p> 
  5. {% endif %} 

Python 的“真值”

在Python和Django模板系統中,以下這些對象相當于布爾值的False

空列表([] )

空元組(() )

空字典({} )

空字符串('' )

零值(0 )

特殊對象None

對象False(很明顯)

提示:你也可以在自定義的對象里定義他們的布爾值屬性(這個是python的高級用法)。

除以上幾點以外的所有東西都視為`` True``

{% if %} 標簽接受 and , or 或者 not 關鍵字來對多個變量做判斷 ,或者對變量取反( not ),例如: 例如:

 

 
  1. {% if athlete_list and coach_list %} 
  2. Both athletes and coaches are available. 
  3. {% endif %} 
  4.  
  5. {% if not athlete_list %} 
  6. There are no athletes. 
  7. {% endif %} 
  8.  
  9. {% if athlete_list or coach_list %} 
  10. There are some athletes or some coaches. 
  11. {% endif %} 
  12.  
  13. {% if not athlete_list or coach_list %} 
  14. There are no athletes or there are some coaches. 
  15. {% endif %} 
  16.  
  17. {% if athlete_list and not coach_list %} 
  18. There are some athletes and absolutely no coaches. 
  19. {% endif %} 

{% if %} 標簽不允許在同一個標簽中同時使用 and 和 or ,因為邏輯上可能模糊的,例如,如下示例是錯誤的: 比如這樣的代碼是不合法的:

 

 
  1. {% if athlete_list and coach_list or cheerleader_list %} 

系統不支持用圓括號來組合比較操作。 如果你確實需要用到圓括號來組合表達你的邏輯式,考慮將它移到模板之外處理,然后以模板變量的形式傳入結果吧。 或者,僅僅用嵌套的{% if %}標簽替換吧,就像這樣:

 

 
  1. {% if athlete_list %} 
  2. {% if coach_list or cheerleader_list %} 
  3. We have athletes, and either coaches or cheerleaders! 
  4. {% endif %} 
  5. {% endif %} 

多次使用同一個邏輯操作符是沒有問題的,但是我們不能把不同的操作符組合起來。 例如,這是合法的:

 

 
  1. {% if athlete_list or coach_list or parent_list or teacher_list %} 

并沒有 {% elif %} 標簽, 請使用嵌套的`` {% if %}`` 標簽來達成同樣的效果:

 

 
  1. {% if athlete_list %} 
  2. <p>Here are the athletes: {{ athlete_list }}.</p> 
  3. {% else %} 
  4. <p>No athletes are available.</p> 
  5. {% if coach_list %} 
  6. <p>Here are the coaches: {{ coach_list }}.</p> 
  7. {% endif %} 
  8. {% endif %} 

一定要用 {% endif %} 關閉每一個 {% if %} 標簽。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 密山市| 灵丘县| 庄浪县| 金寨县| 三门峡市| 会宁县| 山阴县| 延庆县| 房山区| 福泉市| 赣州市| 合川市| 阿拉善左旗| 井冈山市| 武安市| 焦作市| 黔西县| 墨玉县| 孙吴县| 伊金霍洛旗| 云浮市| 册亨县| 武陟县| 大洼县| 临泽县| 永善县| 屏山县| 黔西县| 武平县| 罗城| 丽江市| 林西县| 洞头县| 自贡市| 和硕县| 湖口县| 大城县| 手游| 延长县| 景德镇市| 高安市|