PrashantMaheshw
2 years agoQrew Captain
(Solved) JINJA - Using a Counter inside Loop
TIL ,
PS : I'm aware you can use loop.index but there was scenario involving where I couldn't .
You cannot use a simple counter variables inside ninja loops. Case in Point
{% set x = 0 %}
Counter Value before loop {{x}}
{% for myloop in range(6) %}
{% x=x+1 %}
{%end for%}
Counter Value after loop {{x}}
You would expect the output to be
Counter value before loop 0
1
2
3
4
5
Counter value after loop 5
Instead what we get it is
Counter value before loop 0
1
1
1
1
1
1
Counter value after loop 0
Everything inside loop gets a fresh value of our counter X in case
---
After some painful searching I stumbled upon a Ninja function called namespace for solving exactly the same issue
{% set x = namespace(value=0) %}
Counter Value before loop {{x}}
{% for myloop in range(6) %}
{% x.value=x.value+1 %}
{%end for%}
Counter Value after loop {{x}}
Now the output is
Counter value before loop 0
1
2
3
4
5
Counter value after loop 5
------------------------------
Prashant Maheshwari
------------------------------
PS : I'm aware you can use loop.index but there was scenario involving where I couldn't .
You cannot use a simple counter variables inside ninja loops. Case in Point
{% set x = 0 %}
Counter Value before loop {{x}}
{% for myloop in range(6) %}
{% x=x+1 %}
{%end for%}
Counter Value after loop {{x}}
You would expect the output to be
Counter value before loop 0
1
2
3
4
5
Counter value after loop 5
Instead what we get it is
Counter value before loop 0
1
1
1
1
1
1
Counter value after loop 0
Everything inside loop gets a fresh value of our counter X in case
---
After some painful searching I stumbled upon a Ninja function called namespace for solving exactly the same issue
{% set x = namespace(value=0) %}
Counter Value before loop {{x}}
{% for myloop in range(6) %}
{% x.value=x.value+1 %}
{%end for%}
Counter Value after loop {{x}}
Now the output is
Counter value before loop 0
1
2
3
4
5
Counter value after loop 5
------------------------------
Prashant Maheshwari
------------------------------