簡體   English   中英

如何在 Jinja 2 中使用條件 if 語句?

[英]How to use conditional if statements in Jinja 2?

所以我是 Django 的新手,可以使用一些幫助。 我使用了 for 循環來顯示我的數據庫中的列表。 但我想添加一個 if 語句,如果用戶輸入與我的數據庫項目匹配,那么它才應該被顯示。 看看:

{%for inc in all_items%}
    <ul>                 
        {#I want to add an if statement here, if user input == inc_element#}
        <li><p>{{inc.item_name}}<p></li>
    </ul>
    <hr>
{%endfor%}

我知道我必須使用 HTML 論壇來獲取用戶輸入。 但是我如何在 if 語句中匹配它。 幫助將不勝感激。

一般條件語法是這樣的:

{% if some_variable == some_value %}
    {{ do_something }}
{% endif %}

文檔有更多示例

注意:混亂是一個變量

下面是在 Python 語言中使用“for 循環”和“if 語句”以及 HTML 文件中的 Jinja 的代碼語法:

{% for mess in get_flashed_messages() %}
    {%if mess == "Your Dog's breed is rufus"%}
      {{mess}} 
    {% else %}
      {{"Don't you have any other breed?"}}
      {% endif %}      
    {% endfor %}

下面是在 HTML 文件中使用 Jinja 和 Bootstrap 時的代碼:

{% for mess in get_flashed_messages() %}
    {%if mess == "Your Dog's breed is rufus"%}
     <div class="alert alert-warning alert-dismissible fade show" role="alert">
      {{mess}} 
    {% else %}
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
      {{"Don't you have any other breed?"}}
      {% endif %}      
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div> 
    </div>
    {% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM