Template Sensor with if then for unit_of_measurement

I’ve tried to create a template sensor with 2 differnt units of measurement and calculating state (value) depending. Even as state works fine, unit of measurement shows me the hole template string instead of “kWh” or “Wh”:

 - sensor: 
      - name: "Batterie entladen heute"
        unit_of_measurement: >
            {% if states('sensor.today_batt_discharge') | float > 1000 %}
              "kWh"
            {% else %}
              "Wh"
            {% endif %}
        state: >                                   
            {% if states('sensor.today_batt_discharge') | float > 1000 %}
              {% set state = states('sensor.today_batt_discharge') %}{{ (state | float / 1000 | round (1) if is_number(state))}}
            {% else %}
              {% set state = states('sensor.today_batt_discharge') %}
            {% endif %} aste code here

unit_of_measurement is not template-enabled, for at least a good reason: entities are not supposed to have “variable” units

1 Like

For future reference, the documentation indicates if an option can accept a template.

1 Like

Thanks for your answers, I missedd / missunderstood the documentation a little bit :thinking:

There is a work around using node red. You can create a node red sensor and update units as you wish.

1 Like