Executing a Jinja2 Loop for a Subset of Elements

Imagine you want to create a Jinja2 report that includes only a select subset of elements of a data structure… and want to have header, footer, and element count in that report.

Traditionally we’d solve that challenge with an extra variable, but as Jinja2 variables don’t survive loop termination, the code to do that in Jinja2 gets exceedingly convoluted.

Fortunately, Jinja2 provides a better way: using a conditional expression to select the elements you want to iterate over.

1 comments:

  1. It looks like a list comprehension in Python. I wonder if the underlying data structure is a generator.
Add comment
Sidebar