In this topic, we will figure out the purpose of loops in Jinja. It's a very powerful tool to generate beautiful and convenient web pages. If you have a general understanding of Jinja conditions, the concept of loops will be pretty easy, rest assured! First of all, remember the usual Python syntax: Jinja loops work the same; you just need to frame the code in special characters: {% %}:
<!DOCTYPE html>
<html>
<head>
<title>Mega Template</title>
</head>
<body>
<h1>Checklist</h1>
{% for item in checklist %}
<p>{{ item }}</p>
{% endfor %}
</body>
</html>You can see that we use a default Python for loop as if we were working with array elements: we iterate through them and create an HTML paragraph element for each where we insert the value of each element with the {{ }} symbols. When we work with the built-in constructions such as loops (and conditions), we use {% %} as a notation, but when inserting some variable values, we specify them in double curly brackets {{ }}. Don't forget to close a loop with {% endfor %}.
Advanced loops
Jinja also supports nested loops! They give you a lot of new features, especially if combined with a beautiful frontend. Let's see:
<!DOCTYPE html>
<html>
<head>
<title>Mega Template</title>
</head>
<body>
<h1>EventTable Managment</h1>
{% for record in eventtable %}
<ol>
{% for event in record %}
<li>{{ event }}</li>
{% endfor %}
</ol>
{% endfor}
</body>
</html>The snippet above is fairly simple: Python inside HTML. Let's take a look at something more complicated: we work with lists, but sometimes we need to work with dictionaries, too. Can we do this with Jinja? Of course! We can get values from a dictionary with well-known Python commands: .values(), .keys() and .items()
<!DOCTYPE html>
<html>
<head>
<title>Mega Template</title>
</head>
<body>
<h1>Tasklist</h1>
{% for time, task in tasks.items() %}
<p>{{ time }} - {{ task }}</p>
{% endfor}
</body>
</html>We can get all key-value pairs from the dictionary and generate a key-value string for each. For this, we need to include the p tag to display a web page correctly.
Conclusion
Today, we've learned how to create beautiful dynamic web pages using Jinja language! You can use it for lists and dictionaries, and, of course, for individual variables, too. Sometimes, using loops can save a lot of time and nerves. Good luck!