Struggling with variables within a Template

Hi all,

I try to get the best possible 3-hour window to charge my PV battery by calculating the cheapest window

I have stored the tomorrow prices in an attribute tomorrow in a sesnor tibber_prices.

My template always gives the 00:00-03:00 window as the ceapest and I think this is because the template forgets about the values set within the for loop.
The output of {{min_price}} after the look is 999999 always but the output within the

{% set prices = state_attr('sensor.tibber_prices', 'tomorrow') %}
{% if prices %}
  {% set min_price = 999999 %}
  {% set min_window_start = 0 %}
  {% for i in range(0, prices | length - 2) %}
    {% set window_price = prices[i].total + prices[i + 1].total + prices[i + 2].total %}
    {% if window_price < min_price %}
      befor set {{ min_price }}
      {% set min_price = window_price %}
      {% set min_window_start = i %}
      {{ min_price }}
    {% endif %}

  {% endfor %}
  {{ min_window_start }}:00 - {{ min_window_start + 3 }}:00
{% else %}
   No price data available
{% endif %}

This result in

      befor set 999999

      0.7323999999999999

      befor set 999999

      0.7188

      befor set 999999
      
      0.7162

Which tells me that even in each loop of the for the set variables from before are taken.
Does anybody know how I can do this properly ?

br
distel

You need to use namespace for defining the variables that will be used within the for-loop.

2 Likes