Jinja2 variable out of scope

257 Views Asked by At

I've the following template:

{% set rotator = 1 %}
{% for idx in range(1, count|int + 1) %}
{% if rotator == 4 %}
  {% set rotator = 1 %}
{% endif %}
{
  "id": "{{ '%02d' % idx }}",
  "value": "{{rotator}}"
},
{% set rotator = rotator + 1 %}
{% endfor %}

this template doesn't work because of the issue discussed here How to increment a variable on a for loop in jinja template? For doesn't work I mean that the rotator is always one and doesn't change.

How then could I overcome to the following issue?

1

There are 1 best solutions below

0
On BEST ANSWER

The template:

{% for idx in range(1, count|int + 1) %}
{
  "id": "{{ '%02d' % idx }}",
  "value": "{{ (idx+2)%3+1 }}"
},
{% endfor %}

The result (for count=7):

{
  "id": "01",
  "value": "1"
},
{
  "id": "02",
  "value": "2"
},
{
  "id": "03",
  "value": "3"
},
{
  "id": "04",
  "value": "1"
},
{
  "id": "05",
  "value": "2"
},
{
  "id": "06",
  "value": "3"
},
{
  "id": "07",
  "value": "1"
},

I leave the ending , because you did not specify what to do with it either.