Error on template when attributes are empty

I’m using Owntracks to push battery data from my phone via MQTT to HA. I then created a template to push the mattery value to its own sensor so I can track the number over time. This works except on startup of HA when the initial sensor exists but has not attributes yet I get the error thrown:

Template variable error: ‘None’ has no attribute ‘attributes’ when rendering

The template I am using is:

    gtab_battery:
      friendly_name: GTab Battery
      unit_of_measurement: "%"
      value_template: "{{ state_attr('device_tracker.gtab', 'battery_level') }}"   
      icon_template: >-
        {% set battery_level = states.device_tracker.gtab.attributes.battery_level | default(0) | int %}
        {% set battery_round = (battery_level|int / 10)|int * 10 %}
          {% if battery_round >= 100 %}
            mdi:battery
          {% elif battery_round > 0 %}
            mdi:battery-{{ battery_round }}
          {% else %}
            mdi:battery-alert
        {% endif %}

I did have an availability_template but as the sensor seems to get created by the addon and is empty at launch this didn’t stop the error.

Having read a lot of posts on the same error I am still struggling to find a way to stop them throwing an error and would really like a cleaner log file! Suggestions please.

You can apply the default in the int filter.

      icon_template: >-
        {% set battery_level = state_attr('device_tracker.gtab','battery_level') | int(0) %}

Also:

https://www.home-assistant.io/docs/configuration/templating/#states

You probably should set a default here too:

value_template: "{{ state_attr('device_tracker.gtab', 'battery_level')|float(0) }}" 

Thanks. I tried making sure the defaults were everywhere but still throws the same error. Is there a way to add a delay as it looks like the data is set up within 5 secs of when it runs then think it will be fine.

Show what you have now.

Actually - al good now - I’d missed swapping one of the state values to state_attr and all works well. Thanks.

you could also add the device_class: battery, and delete the icon_template.

this is what I use:

      - unique_id: owntracks_theboss_battery_level
        name: Owntracks Boss battery level
        unit_of_measurement: '%'
        state: >
          {{state_attr('device_tracker.owntracks_theboss','battery_level')}}
        device_class: battery

the default seems to not be required because no conversion is happening. I say ‘seems’ because I am not 100% certain. There never is a warning/error though, so probably fine :wink:

btw, do note I use the new template: format, and you’re still using the legacy platform: template format

1 Like

Thanks for the battery tip - I can clean up a number of templates! Next stop is the conversion of format now I have no errors.