Issue with state_attr and objects in template

I’m a bit stumped, reading from other examples this should work:

{% for object in states.binary_sensor %}
{% set battery = state_attr(object , 'battery_level') %}
{{object.name}}:{{battery}}
{% endfor %}

however it gives this strange error in the log:

File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/helpers/template.py", line 284, in __getattribute__
    return getattr(object.__getattribute__(self, '_state'), name)
AttributeError: 'State' object has no attribute 'lower'

for reference, this works:

{% for object in states.binary_sensor %}
{{object}}
{% endfor %}

And gives output, including the asked battery level (shortend):

<template state binary_sensor.motion_sensor_158d0002b8586b=off; No motion since=1800, device_class=motion, battery_level=49.0, friendly_name=motion_trap @ 2019-02-02T09:09:19.440280+01:00> 
<template state binary_sensor.ring_front_door_ding=off; friendly_name=Front Door Ding, expires_at=2019-02-02T12:08:21.668320+01:00, firmware=Up to Date, device_class=occupancy, state=ringing, device_id=341513c2b0af, attribution=Data provided by Ring.com, timezone=Europe/Amsterdam @ 2019-01-31T11:41:46.618673+01:00>

Na, that won’t work. You’re iterating across state objects and passing the state object to the function. You need to pass the entity_id to the function.

{% for object in states.binary_sensor %}
{% set battery = state_attr(object.entity_id, 'battery_level') %}
{{object.name}}:{{battery}}
{% endfor %}

Yeah that works because the state object has a repr function. That repr function properly prints objects as strings for users. But you are seeing a representation of the entire object.

1 Like

Thanks, I wasn’t aware. Also some of the examples that I found on here were wrong also in that case.

where’d you find the examples? Many people don’t know what they are doing with templates, they just copy/paste. Best to always consult the examples on HA’s templating pages or ask here.

looks like they reworked the help page. All these examples look good.

examples in forum posts. The examples in the documentation are fine, but they don’t give examples like this.