Counting with Jinja Template doesn't work

Hi,
I’m trying to use an incremental variable with a loop but can’t figure out why it doesn’t work.
Here is a simple script (that I call with a lovelace button) in my script.yaml

get_total:
  alias: "Get Total"
  sequence:
    - service: persistent_notification.create
      data:
        title: Test TOTAL
        message: >-
            {% set total = 0 %}
            total value start : {{ total }}
            {% for i in range(0,10) %}
              {% set total = total + 1 %}
              i value : {{ i }}
              total value : {{ total }}
            {% endfor %}
            total value end : {{ total }}

And here is what I get as result :

Test TOTAL
total value start : 0

i value : 0
total value : 1

i value : 1
total value : 1

i value : 2
total value : 1

i value : 3
total value : 1

i value : 4
total value : 1

i value : 5
total value : 1

i value : 6
total value : 1

i value : 7
total value : 1

i value : 8
total value : 1

i value : 9
total value : 1
total value end : 0

Why total variable is not incremented in this simple loop ? :face_with_raised_eyebrow:

Thanks for your help !

You need to use a namespace to extract values out of a loop.

get_total:
  alias: "Get Total"
  sequence:
    - service: persistent_notification.create
      data:
        title: Test TOTAL
        message: >-
            {% set ns = namespace(total = 0) %}
            total value start : {{ ns.total }}
            {% for i in range(0,10) %}
              {% set ns.total = ns.total + 1 %}
              i value : {{ i }}
              total value : {{ ns.total }}
            {% endfor %}
            total value end : {{ ns.total }}

Thanks, it works !
Until now, I only used basi Jinga. I’m going to learn more about namespace to understand that. :+1:

See “Scoping Behaviour” under this section:

https://jinja.palletsprojects.com/en/latest/templates/#assignments