Cannot cast attribute in template sensor

Hi, this should be a simple thing but I really can’t figure out why I’m unable to cast an attribute from a template sensor.

The simplest case in which I can reproduce this issue is as follows:

- sensor:
  - name: Testing
    state: "{{ this.attributes.x | int }}"
    attributes:
      x: "200"

This sensor works when I remove the | int, but as soon as I add that I get unavailable. I really do not understand what is happening here.


For reference, here’s what I’m actually trying to do:

- binary_sensor:
    # Track whether there is enough day light
    - &day_light
      name: Day Light
      device_class: light
      icon: mdi:theme-light-dark
      state: >
        {% set lux = states('sensor.backyard_motion_sensor_illuminance_lux') %}
        {% if is_number(lux) %}
          {{ lux | int > this.attributes.threshold | int }}
        {% else %}
          {# use sun state when lux not available #}
          {{ is_state('sun.sun', 'above_horizon') }}
        {% endif %}
      attributes:
        threshold: "200"
    - name: Day Light Indoor
      attributes:
        threshold: "400"
      <<: *day_light
      - name: Day Light
        <<: &day_light
          device_class: light
          icon: mdi:theme-light-dark
          state: >
            {% set lux = states('sensor.backyard_motion_sensor_illuminance_lux') %}
            {% if is_number(lux) and this.attributes.threshold is defined %}
              {{ lux | int > this.attributes.threshold | int }}
            {% else %}
              {{ is_state('sun.sun', 'above_horizon') }}
            {% endif %}
        attributes:
          threshold: 200
      - name: Day Light Indoor
        attributes:
          threshold: 400
        <<: *day_light

This won’t fix the problem I’m afraid. As I said, if I remove the | int from the isolated example, the sensor returns the value of the attribute, so it not being defined in the first place is not the problem.

I may be misunderstanding your response, but it seems to be working on my end using an input number as a sub for the sensor… In the following the input number was set to 220, but both binary sensors behave as expected when it is set below 200 and above 400 as well.

I’ve tried it and you’re right, it does seem to fix the problem, but I still don’t understand why mine wasn’t working. Either way, this is enough for me to move forward and further troubleshoot what I was doing wrong. Thank you!

There have been issues in the past with template rendering, self-referencing, and load order. The basic advice I remember was to always check if the self-referenced variable is defined and/or always provide a default value. I haven’t really kept up with the issue so I don’t know if either of those are no longer needed. In your “simple case”, if the attributes are unloaded when the template renders it will error out because your int does not have an explicit default value.

1 Like