Python 如何在 Jinja 2 中使用条件 if 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48169611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:34:46  来源:igfitidea点击:

How to use conditional if statements in Jinja 2?

pythondjangodjango-templatesjinja2

提问by Arjun Kashyap

So I am new to Django and can use some help. I have used a for loop to display a list from my database. But I want to add an if statement such that, if the user input matches my database item, only then it should be displayed. Take a look :

所以我是 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%}

I know I 'd have to use HTML forums for taking user input. But how do I match it in if statement. Help would be appreciated.

我知道我必须使用 HTML 论坛来获取用户输入。但是我如何在 if 语句中匹配它。帮助将不胜感激。

回答by xyres

General conditional syntax is like this:

一般条件语法是这样的:

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

Docs have some more examples.

文档有更多示例