Jinja templating and variable scope

I have solar in my new house, and when I have excess power I want to display a markdown card to give me suggestions on how to use it. One of the most important things is my electric radiators, because my gas price is ridiculous and it’s cheaper to run the electric radiators.

I’ve tried the following in a markdown card, but it seems remaining_power amendments aren’t persisted through the for loop. I don’t know enough about Jinja to work around this… any suggestions? I’d expect the ‘after’ for each iteration to be pulled into the ‘before’ for the next one

Thanks!

{% set excess_power = states('sensor.solax_7d8efb09_exported_power') | float %} 

Current excess power: {{ excess_power }} W

{% set heaters = [
  {'name': 'Hall Heater', 'power': 250.0},
  {'name': 'Shower Heater', 'power': 250.0},
  {'name': 'Dining Room Heater', 'power': 750.0},
  {'name': 'Bedroom Heater', 'power': 750.0},
  {'name': 'Living Room Heater', 'power': 750.0},
  {'name': 'X Heater', 'power': 750.0},
  {'name': 'Office Heater', 'power': 750.0}
] %}

{% set remaining_power = excess_power %} 

{% for heater in heaters %}
  {% set heater_entity = 'switch.' ~ heater.name | lower | replace(' ', '_') %}
  {% set heater_state = states(heater_entity) %}
  
  {% if heater_state != 'on' %}
    {% if remaining_power >= heater.power %}
  - Turn on the {{ heater.name }}
      before: {{ remaining_power }}
      {% set remaining_power = remaining_power - heater.power %}
      after: {{ remaining_power }}
    {% else %}
      - Not enough excess power for the {{ heater.name }}
    {% endif %}
  {% else %}
    - {{ heater.name }} is already on.
  {% endif %}
{% endfor %}

{% if remaining_power < 750 %}
  There isn't enough excess solar power to turn on any heaters.
{% endif %}

Output:

Current excess power: 1372.0 W

Turn on the Hall Heater
before: 1372.0

after: 1122.0

Turn on the Shower Heater
before: 1372.0

after: 1122.0

Turn on the Dining Room Heater
before: 1372.0

after: 622.0

Turn on the Bedroom Heater
before: 1372.0

after: 622.0

Turn on the Living Room Heater
before: 1372.0

after: 622.0

Turn on the X Heater
before: 1372.0

after: 622.0

Turn on the Office Heater
before: 1372.0

after: 622.0

Variables have local scope, see: https://www.home-assistant.io/docs/scripts/#scope-of-variables

yeah I guess that’s kinda what I worked out after a bit of toing and froing.

can you think of an alternative way to achieve what I’m trying to do?

You can use helpers or there is a global variable 3rd party integration or you could implement something like this: WTH can't input helpers be read only in UI - #13 by TheFes