Template and "this"

Hope someone can help me to understand.
I have several templates which build with the following pattern:

template:
  - sensor:
  - name: "AZ HC power"
    unique_id: "az_hc_power"
    unit_of_measurement: "W"
    attributes:
      radiatorpower: "2782"
    state: >
      {% set pers = states('sensor.az_thermostat_valve_state') | float (0) %}   
      {% set power = state_attr("sensor.az_hc_power","radiatorpower") | float (-1) %} 
      {% if pers == 'unknown' %}
        0
      {%- else %}  
        {{ (power*pers/100) |round(0) | int }}
      {% endif %}

As
My understanding: this. can be a reference to the current sensor:
so:

  {% set power = state_attr("sensor.az_hc_power","radiatorpower") | float (-1) %} 
  {% set power = this.attributes.radiatorpower | float (-1) %} 

shall lead to the same result, but lead to some kind of error.
Can someone give me a hint ?

By the way: Would it be possible to add to expand an integrated sensor by additional attributes and do such calculations instead of having a dedicated template ? E.g. the homematic thermostat ?

thank you
Peter

States are usually loaded before attributes, add a default to your power variable to guard against errors caused by undefined attributes.

Also, your indents are off and attributes can be integers or floats, reducing the need to convert them in later templates.

template:
  - sensor:
    - name: "AZ HC power"
      unique_id: "az_hc_power"
      unit_of_measurement: "W"
      attributes:
        radiatorpower: 2782
      state: >
        {% set pers = states('sensor.az_thermostat_valve_state') | float(0) %}   
        {% set power = this.attributes.radiatorpower | default(2782) %} 
        {{ (power * pers / 100) | round(0) | int }}

EDIT: Corrected “unknown” issue pointed out below. Thanks @Ildar_Gabdullin.

1 Like

Can this condition be true if the “pers” value is “… | float(0)”?

1 Like

Thank you very much !
I tested it and it works finde. Only drawback:
I have several of those templates and only want to change as less as possible inside of the template to have more or less the same “code”. If I use the e.g. instead of “default(2782)” (the number is different for each template) with “default(0)” I got no error but the value is wrong until the value “sensor.az_thermostat_valve_state” changes the next time.
So I can use this, but unfortunately it has no advantage in this case.

Nevertheless I learnd something ! One additional topic is, that my cool idea with the " {% if pers == ‘unknown’ %}" will not work because the problem that I I would like to avoid occurs while float conversion.

thank you
Peter