新聞中心
本篇文章為大家展示了怎么用Django中的{%if%} ,代碼簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
10年積累的網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有陸河免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
{% if %} 標(biāo)簽檢查(evaluate)一個(gè)變量,如果這個(gè)變量為真(即,變量存在,非空,不是布爾值假),系統(tǒng)會顯示在 {% if %} 和 {% endif %} 之間的任何內(nèi)容。
例如:
{% if today_is_weekend %}Welcome to the weekend!
{% endif %}
{% else %} 標(biāo)簽是可選的:
{% if today_is_weekend %}Welcome to the weekend!
{% else %}Get back to work.
{% endif %}
Python 的“真值”
在Python和Django模板系統(tǒng)中,以下這些對象相當(dāng)于布爾值的False
空列表([] )
空元組(() )
空字典({} )
空字符串('' )
零值(0 )
特殊對象None
對象False(很明顯)
提示:你也可以在自定義的對象里定義他們的布爾值屬性(這個(gè)是python的高級用法)。
除以上幾點(diǎn)以外的所有東西都視為`` True``
{% if %} 標(biāo)簽接受 and , or 或者 not 關(guān)鍵字來對多個(gè)變量做判斷 ,或者對變量取反( not ),例如: 例如:
{% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if not athlete_list or coach_list %} There are no athletes or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %}
{% if %}標(biāo)簽不允許在同一個(gè)標(biāo)簽中同時(shí)使用 and 和 or ,因?yàn)檫壿嬌峡赡苣:?,例如,如下示例是錯(cuò)誤的: 比如這樣的代碼是不合法的:
{% if athlete_list and coach_list or cheerleader_list %}
系統(tǒng)不支持用圓括號來組合比較操作。 如果你確實(shí)需要用到圓括號來組合表達(dá)你的邏輯式,考慮將它移到模板之外處理,然后以模板變量的形式傳入結(jié)果吧。 或者,僅僅用嵌套的{% if %}標(biāo)簽替換吧,就像這樣:
{% if athlete_list %} {% if coach_list or cheerleader_list %} We have athletes, and either coaches or cheerleaders! {% endif %} {% endif %}
多次使用同一個(gè)邏輯操作符是沒有問題的,但是我們不能把不同的操作符組合起來。 例如,這是合法的:
{% if athlete_list or coach_list or parent_list or teacher_list %}
并沒有 {% elif %} 標(biāo)簽, 請使用嵌套的`` {% if %}`` 標(biāo)簽來達(dá)成同樣的效果:
{% if athlete_list %}Here are the athletes: {{ athlete_list }}.
{% else %}No athletes are available.
{% if coach_list %}Here are the coaches: {{ coach_list }}.
{% endif %} {% endif %}
一定要用 {% endif %} 關(guān)閉每一個(gè) {% if %} 標(biāo)簽。
上述內(nèi)容就是怎么用Django中的{%if%} ,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當(dāng)前標(biāo)題:怎么用Django中的{%if%}
網(wǎng)址分享:http://www.dlmjj.cn/article/gjishd.html