电竞比分网-中国电竞赛事及体育赛事平台

分享

在Django模板中的 if else endif

 怎么了啊早上 2014-04-20

if/else

{% if %} 標(biāo)簽檢查(evaluate)一個(gè)變量,如果這個(gè)變量為真(即,變量存在,非空,不是布爾值假),系統(tǒng)會(huì)顯示在 {% if %}{% endif %} 之間的任何內(nèi)容,例如:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% endif %}

{% else %} 標(biāo)簽是可選的:

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

Python 的“真值”

在Python和Django模板系統(tǒng)中,以下這些對(duì)象相當(dāng)于布爾值的False

  • 空列表([] )

  • 空元組(() )

  • 空字典({} )

  • 空字符串('' )

  • 零值(0 )

  • 特殊對(duì)象None

  • 對(duì)象False(很明顯)

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

除以上幾點(diǎn)以外的所有東西都視為`` True``

5

{% if %} 標(biāo)簽接受 and , or 或者 not 關(guān)鍵字來對(duì)多個(gè)變量做判斷 ,或者對(duì)變量取反( not ),例如: 例如:

6

{% 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í)使用 andor ,因?yàn)檫壿嬌峡赡苣:?,例如,如下示例是錯(cuò)誤的: 比如這樣的代碼是不合法的:

{% if athlete_list and coach_list or cheerleader_list %}

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

4

{% if athlete_list %}
    {% if coach_list or cheerleader_list %}
        We have athletes, and either coaches or cheerleaders!
    {% endif %}
{% endif %}

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

6

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

并沒有 {% elif %} 標(biāo)簽, 請使用嵌套的`` {% if %}`` 標(biāo)簽來達(dá)成同樣的效果:

6

{% if athlete_list %}
    <p>Here are the athletes: {{ athlete_list }}.</p>
{% else %}
    <p>No athletes are available.</p>
    {% if coach_list %}
        <p>Here are the coaches: {{ coach_list }}.</p>
    {% endif %}
{% endif %}

一定要用 {% endif %} 關(guān)閉每一個(gè) {% if %} 標(biāo)簽。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請遵守用戶 評(píng)論公約

    類似文章 更多