詳解Django中的ifequal和ifnotequal標籤使用

來源:互聯網
上載者:User
Django模板系統壓根兒就沒想過實現一個全功能的程式設計語言,所以它不允許我們在模板中執行Python的語句(還是那句話,要瞭解更多請參看理念和限制小節)。 但是比較兩個變數的值並且顯示一些結果實在是個太常見的需求了,所以Django提供了 {% ifequal %} 標籤供我們使用。

{% ifequal %} 標籤比較兩個值,當他們相等時,顯示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。

下面的例子比較兩個模板變數 user 和 currentuser :

{% ifequal user currentuser %}  

Welcome!

{% endifequal %}

參數可以是硬式編碼字串,隨便用單引號或者雙引號引起來,所以下列代碼都是正確的:

{% ifequal section 'sitenews' %}  

Site News

{% endifequal %}{% ifequal section "community" %}

Community

{% endifequal %}

和 {% if %} 類似, {% ifequal %} 支援可選的 {% else%} 標籤:

{% ifequal section 'sitenews' %}  

Site News

{% else %}

No News Here

{% endifequal %}

只有模板變數,字串,整數和小數可以作為 {% ifequal %} 標籤的參數。下面是合法參數的例子:

{% ifequal variable 1 %}{% ifequal variable 1.23 %}{% ifequal variable 'foo' %}{% ifequal variable "foo" %}

其他任何類型,例如Python的字典類型、清單類型、布爾類型,不能用在 {% ifequal %} 中。 下面是些錯誤的例子:

{% ifequal variable True %}{% ifequal variable [1, 2, 3] %}{% ifequal variable {'key': 'value'} %}

如果你需要判斷變數是真還是假,請使用 {% if %} 來替代 {% ifequal %} 。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.