Template loop error when raising existing value

Hi,

I have a newbie question:
I created a template sensor named “sensor.true_grid_energy_in” to combine 2 energy sensors measurement values (kWh within a certain time period) to a single one subtracting one from the other and adding the result to the existing value of that sensor.

This is the template:

{% if states('sensor.grid_energy_in_helper_counter') not in ['none', 'unknown', 'unavailable']
          or states('sensor.grid_energy_out_helper_counter') not in ['none', 'unknown', 'unavailable'] %}

  {%- set saldo = (state_attr('sensor.grid_energy_in_helper_counter', 'last_period') | float(0)) - (state_attr('sensor.grid_energy_out_helper_counter', 'last_period') | float(0))  -%}

{% else %}
  {%- set saldo = 0 -%}
{% endif %}

{% if saldo < 0 %}
  {%- set saldo = 0 -%}
{% endif %}

{%- set value = states('sensor.true_grid_energy_in') | float(0) -%}

{%- set result = (value + saldo ) | float(0) -%}

{{ result }}

This leads to a template loop warning because it references the sensor itself.

To all the professionals out there:
What would be the best solution for that task?

Thanks.

Use this.state (with filters as needed) to self-reference (docs).

Won’t work in the developer tools template editor.

Don’t you want both tests in the first if to be true?

I’ve started to use has_value to test this, but not sure that covers all the possibilities.