WTH there are still no any generic template or template functions?

Hello.

Currently, I am actively using really cool feature of HA - template entities (sensors, binary_sensors, etc.). But after creating another new template every time I wonder, why there are so huge amount of “copy-paste” code produced?

For example, I have about 20 Aqara wall switches and I need to calculate power usage for every single button separately. Below is a code example which I use to achieve that.

  template:
    - sensor:
        # Right switch power
        - name: 0x00158d00054a2222_right_power
          unique_id: template.sensor.0x00158d00054a2222_right_power
          state: >-
            {% set power = 0.0 -%}
            {% if is_state('switch.0x00158d00054a2222_right','on') -%}
                {% set power = states('sensor.0x00158d00054a2222_power') | float(0.0) -%}
                {% if is_state('switch.0x00158d00054a2222_left','on') -%}
                    {% set power = [25.0, power] | min -%}
                {% endif -%}
            {% endif -%}
            {{ power | round(2) }}
          state_class: measurement
          unit_of_measurement: W
          device_class: power

        # Left switch power
        - name: 0x00158d00054a2222_left_power
          unique_id: template.sensor.0x00158d00054a2222_left_power
          state: >-
            {% set power = 0.0 -%}
            {% if is_state('switch.0x00158d00054a2222_left','on') -%}
                {% set power = states('sensor.0x00158d00054a2222_power') | float(0.0) -%}
                {% if is_state('switch.0x00158d00054a2222_right','on') -%}
                    {% set power = [power - 25.0, 0.0] | max -%}
                {% endif -%}
            {% endif -%}
            {{ power | round(2) }}
          state_class: measurement
          unit_of_measurement: W
          device_class: power

There is no difference in logic for calculating the “state” property of each sensor. It would be nice to have a way to create, let say, “base template” or “generic template” which will be used then by passing necessary parameters to it. Or it could also be some functions or scripts or whatever it could be. Ideally, the desired code should look as simple as this one below:

state: "{{ GetPower('sensor.0x00158d00054a2222_power', 'switch.0x00158d00054a2222_left', 'switch.0x00158d00054a2222_right') }}" 
state_class: measurement

What do think about this?
Thanks!

Duplicate → Reusable Jinja/template helpers - #4 by Soloam