Template attributes

Why is this not valid? Can’t we use the sensor value for the attributes? Or am I doind something wrong?

pl_low_btc:
      value_template: "{{ ((states.sensor.yahoofinance_btc_usd.state|float - states.input_number.low_open_btc.state|float)*100 / states.input_number.low_open_btc.state|float)|round(2) }}"
      unit_of_measurement: "%"
      friendly_name: "Bitcoin Low P/L"
      attributes:
        is_positive: >
          {% if state(sensor.pl_low_btc)|float > 0 %}
            true
          {% else %}
            false
          {% endif %}
        is_10_percent: >
          {% if state(sensor.pl_low_btc)|float > 10 %}
            true
          {% else %}
            false
          {% endif %}

Logger: homeassistant.config
Source: config.py:464
First occurred: 5:08:41 PM (3 occurrences)
Last logged: 5:19:35 PM

Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->pl_low_btc->attributes. (See /config/integrations/…/entities/sensors/stocks_templates.yaml, line 0). Please check the docs at Template - Home Assistant

Incorrect syntax.

Replace attributes with attribute_templates.

In addition, the function is called states() not state().

    pl_low_btc:
      value_template: "{{ ((states('sensor.yahoofinance_btc_usd')|float(0) - states('input_number.low_open_btc')|float(0))*100 / states('input_number.low_open_btc')|float(0))|round(2) }}"
      unit_of_measurement: "%"
      friendly_name: "Bitcoin Low P/L"
      attribute_templates:
        is_positive: "{{ states('sensor.pl_low_btc')|float(0) > 0 }}"
        is_10_percent: "{{ states('sensor.pl_low_btc')|float(0) > 10 }}"

EDIT

Correction. Added missing quotes.

#Facepalm… Thanks.

By the way, this doesn’t work (returns null):

“{{ states(sensor.pl_low_btc)|float > 0 }}”
This does:
“{{ states.sensor.pl_low_btc.state|float > 0 }}”

You’re right; that was due to my mistake. I forgot to wrap the sensor’s entity_id in quotes. I have corrected the example above.

BTW, be advised that it’s preferable to use the states() to get an entity’s state value as opposed to attempting to get it directly using this format: states.sensor.whatever.state

The reason is because if the entity doesn’t exist, the template fails with an error. In contrast, states() will simply report None and the template continues with its evaluation. For more information, refer to the States section of the documentation.

1 Like