32

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.

1
  • 1
    Please accept an answer if your question has been answered. Anything else is rude. Thanks. Commented Jun 8, 2021 at 15:11

2 Answers 2

60

General conditional syntax is like this:

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

Docs have some more examples.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you know how I can store user input into jinja variable
@ArjunKashyap Just pass the user input value to the template context, just like you pass other variables.
@ArjunKashyap This post has just showed up on my screen. It's been bumped because it's not marked as answered. I feel this answer has helped you so please mark it as accepted so that this post does not show up again and other posts without answers can show up.
8

Note: mess is a variable

Below code syntax for using 'for loop' and 'if statements' in Python Language together with Jinja in HTML file:

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

And below is the code if your using Jinja with Bootstrap in HTML file:

{% 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">&times;</span>
        </button>
    </div>
{% endfor %}

1 Comment

FYI: You don't need curly brackets for a text literal. If you omit the quotes, the text will be the output for that portion of the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.