Monday, November 4, 2019

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.


Thanks to Ivan Pepelnjak (see source)

No comments:

Post a Comment