Building network automation solutions

9 module online course

Start now!

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.

We migrated our blog a few days ago, and the commenting functionality is not there yet. In the meantime enjoy the older comments, or find our content on LinkedIn and comment there.


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