Arj*_*yap 0 python django django-templates jinja2
所以我是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%}
Run Code Online (Sandbox Code Playgroud)
我知道我必须使用HTML论坛来获取用户输入.但是如何在if语句中匹配它.帮助将不胜感激.
一般条件语法是这样的:
{% if some_variable == some_value %}
{{ do_something }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
文档有更多的例子.
注意:mess 是一个变量
以下代码语法在 Python 语言中与 Jinja 一起在 HTML 文件中使用“for 循环”和“if 语句”:
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
如果您在 HTML 文件中使用 Jinja 和 Bootstrap,则以下是代码:
{% for mess in get_flashed_messages() %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
{% if mess == "Your Dog's breed is rufus" %}
{{mess}}
{% else %}
{{"Don't you have any other breed?"}}
{% endif %}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)