Trouble creating templates sensor

Hello all,
I’m trying to create a template from a sensor like this

template:
   - sensor:
      - name: battery_consumption
        state: '{% set batter_cons = sensor.solarman_battery_1_power | int  %}
                         {% if batter_cons > 0 %}
                            {{ batter_cons | int }}
                         {% else %}
                            0
                         {% endif %}'
        device_class: power
        unit_of_measurement: W

but I get the following :

Logger: homeassistant.helpers.template_entity
Source: helpers/template_entity.py:393
First occurred: 11:23:25 PM (1 occurrences)
Last logged: 11:23:25 PM

TemplateError('UndefinedError: 'sensor' is undefined') while processing template 'Template("{% set batter_cons = sensor.solarman_battery_1_power | int %} {% if batter_cons > 0 %} {{ batter_cons | int }} {% else %} 0 {% endif %}")' for attribute '_attr_native_value' in entity 'sensor.battery_consumption'

which I’ve found as error in google and in the post there is a suggestion to use somehow “states(sensor.whatever)” but cannot understand how I should do this.

Can someone help me in this task, please ?

Thanks

template:
   - sensor:
       - name: battery_consumption
         state: >
           {% set bc = states('sensor.solarman_battery_1_power') | int(0) %}
           {{ iif(bc > 0, bc, 0) }}
         device_class: power
         unit_of_measurement: W

The line continuation character > indicates the template for state: begins on the next line. The iif in the template is an Immediate If.

Thanks @123
It’s perfect !

Pierluigi

1 Like