HTML if else condition for printing items in list

Viewed 61

I'm making a website with flask, and I pass in a list. My .html file has this code:

{$ for file in list %}
 <div> 
 <img ... > </img>
</div>
{% endfor %}

Now if list.length == 0 I want it to just do something like

<h2> Error </h2>

instead. How do I make an if statement to check if the list is empty, and if it is then I print error on the website, if it is not, I print the images in the list. I tried to put:

<script>
 if(list.length==0){
<h2>Error</h2>
}
else{
"the for loop stuff"
}
</script>

but this does not work. THanks

2 Answers

In Flask with Jinja2 as a template engine, the if-else syntax requires you to write the following statement

{% if mylist.length == 0 %}
    <div>error</div>
{% else %}
    <!-- loop -->
{% endif %}

Note: Since list is a Python keyword i suggest you to use another name for your list in order to avoid possible conflicts.

In this pythonprogramming page about flask 7, you will find some example code and a video. The example shows an if-else statement:

{% for post in posts %}
    <h3> {{ post.title }}</h3>
    <p>{{ post.body }}</p>
 
    {% if author %}
    <span style="font-size:0.5em;color:yellowgreen">{{ post.author }} </span>
    {% endif %}
    
    {% if date %}
    <span style="font-size:0.5em;color:yellowgreen">{{ post.date }}</span>
    {% endif %}
 
{% endfor %}

I decided to post my answer to share this learning resource because I have noted that the example does not use any <script> tag (not sure if it helps).

The comparison operator is almost the same everywhere as you can see in both the Python and Jinja references.

Therefore, the equivalent for your code would be:

{% if list.length == 0 %}
...
{% endif %}
Related