Skip to content
Advertisement

HTML if else condition for printing items in list

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement