0

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?

techraf
  • 64,883
  • 27
  • 193
  • 198
Mazzy
  • 13,354
  • 43
  • 126
  • 207
  • https://fabianlee.org/2016/10/18/saltstack-setting-a-jinja2-variable-from-an-inner-block-scope/ – Mazzy Sep 15 '17 at 22:31
  • So what is the problem you are trying to solve? For example a single change to `"value": "{{rotator - 1 + idx}}"` gives results that one person might deem reasonable. But how is anyone supposed to know what your expectations are? – techraf Sep 15 '17 at 23:11
  • My expectations are that rotator must have the following pattern 1,2,3,1,2,3, etc... – Mazzy Sep 15 '17 at 23:41
  • That's not your expectation, that's an approximation of a solution to a problem introduced by your attempted solution - there's no need for any "`rotator`". – techraf Sep 16 '17 at 01:38

1 Answers1

1

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.

techraf
  • 64,883
  • 27
  • 193
  • 198