Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use conditional if statements in Jinja 2?

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 :

{%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.

like image 465
Arjun Kashyap Avatar asked Jan 09 '18 13:01

Arjun Kashyap


People also ask

How do you write if condition in Jinja?

Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.

How do you write a for loop in Jinja?

For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python. Here my_item is a loop variable that will be taking values as we go over the elements.


1 Answers

General conditional syntax is like this:

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

Docs have some more examples.

like image 55
xyres Avatar answered Oct 12 '22 11:10

xyres