Variables

Jinja Loop Variables

Loop Variables

Jinja loop variables like loop.index track iteration state.

Understanding Jinja Loop Variables

Jinja loop variables are special variables available within for-loops that provide useful information about the current iteration. These variables can help you track the state of the loop, making it easier to work with collections and iterate over them effectively.

Common Jinja Loop Variables

Here are some of the most commonly used loop variables in Jinja:

  • loop.index: The current iteration of the loop (1-based).
  • loop.index0: The current iteration of the loop (0-based).
  • loop.revindex: The number of iterations from the end of the loop (1-based).
  • loop.revindex0: The number of iterations from the end of the loop (0-based).
  • loop.first: Returns True if the current iteration is the first.
  • loop.last: Returns True if the current iteration is the last.
  • loop.length: The total number of iterations in the loop.
  • loop.cycle: A helper function to cycle between a list of sequences.