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
CodePudding user response:
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.
CodePudding user response:
In this pythonprogramming page about flask 7, you will find some example code and a video.
I have noted that the example does not use any <script>
tag and therefore decided to post my answer to share this learning resource (not sure if it helps).
You can see the syntax for if-else statements below (unfortunately not exactly matching your example):
{% 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 %}
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 %}