Sensor is undefined, but it appears to be defined

I have a template sensor to get the relative temperature of the forecast for tomorrow compared to today’s forecast:

- trigger:
    - platform: time
      at: "00:00"
    - platform: event
      event_type: forecast_test
  action:
    - service: weather.get_forecasts
      target:
        entity_id: weather.home
      data:
        type: daily
      response_variable: my_forecast
  sensor:
    - name: Forecast temperature difference - tomorrow [weatherball]
      state: "{{ my_forecast['weather.home'].forecast[1].temperature - my_forecast['weather.home'].forecast[0].temperature }}"
      unit_of_measurement: F

This works. I can see the state in settings and in developer and it is accurate in my testing. I am trying to create an automation based on this sensor, but it keeps giving the error “Error rendering data template: UndefinedError: ‘sensor’ is undefined”

alias: Weatherball
description: ""
trigger:
  - platform: event
    event_type: weatherball_test
condition: []
action:
  - service: light.turn_on
    data:
      color_name: >
        {% if
        states(sensor.forecast_temperature_difference_tomorrow_weatherball) |
        float > 5 %}
          red
        {% elif
        states(sensor.forecast_temperature_difference_tomorrow_weatherball) |
        float < -5 %}
          blue
        {% elif 5 >
        states(sensor.forecast_temperature_difference_tomorrow_weatherball) |
        float > -5 %}
          green
        {% else %}
          white
        {% endif %}
    target:
      device_id: 8afa34b1dd524e9c68fcb5f700cbac2c
mode: single

Why am I getting this error when the state is defined everywhere else?

Get the habit of trying out your templates in developer tools → templates before putting them into a sensor config.

'sensor' is undefined is telling you that you have used a variable named sensor but you didn’t set its value.

You need to put quotes around the entity id if you want it to be interpreted as a string rather than a variable.

states('sensor.my_sensor')

2 Likes

states() takes a string: change states(sensor.blahblah) to states('sensor.blahblah').

I constantly make the same mistake :wink:

Slightly more compact colour template for you:

          {% set x = states('sensor.forecast_temperature_difference_tomorrow_weatherball')|float(999) %}
          {{ { 999 > x > 5:  'red',
               x < -5:       'blue',
               5 >= x >= -5: 'green' }.get(true, 'white') }}

This one uses 999 as a “flag value”, for when the sensor is unavailable or unknown. It also covers the cases of exactly 5 and -5 for which your template will return white, which I assume is unintended?

1 Like

This was it, thanks!