Skip to Content
Mastering Flask Web Development - Second Edition
book

Mastering Flask Web Development - Second Edition

by Daniel Gaspar, Jack Stouffer
October 2018
Intermediate to advanced
332 pages
8h 9m
English
Packt Publishing
Content preview from Mastering Flask Web Development - Second Edition

Loops

We can use loops in Jinja to iterate over any list or generator function, as follows:

{% for post in posts %} 
  <div> 
    <h1>{{ post.title }}</h1> 
    <p>{{ post.text | safe }}</p> 
  </div> 
{% endfor %} 

Loops and if statements can be combined to mimic the break functionality in Python loops. In this example, the loop will only use the post if post.text is not None:

{% for post in posts if post.text %}
  <div>
    <h1>{{ post.title }}</h1>
    <p>{{ post.text | safe }}</p>
  </div>
{% endfor %}

Inside the loop, you have access to a special variable called loop, which gives you access to information about the for loop. For example, if we want to know the current index of the current loop to emulate the enumerate function in Python, we can use the index ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Flask Web Development, 2nd Edition

Flask Web Development, 2nd Edition

Miguel Grinberg
Flask Web Development

Flask Web Development

Miguel Grinberg

Publisher Resources

ISBN: 9781788995405Supplemental Content