States working but state_attr not

Hi all,

I want to get a state attribute based on a variable (for example hard coded) with the entity_id.

              {{ state_attr('switch.shellyplug_1', 'last_changed') }}
              {{ states.switch.shellyplug_1.last_changed }}

The states function return the value, but state_attr not. I’m I doing something wrong?

UPDATE:

Okay I’ve read last_changed is a property and not an attribute. What is the difference between states and state_attr - #6 by tom_l

How can I use a variable in this line then?

{{ states.switch.shellyplug_1.last_changed }}

last_changed isn’t an attribute so that’s why you can’t use state_attr to get its value.

It’s a property of the entity’s state object so if you want its value you reference it like you did in the second template you posted.

I see, I’ve updated my question.

What do you mean by “use a variable in this line”?

Do you want the template to accept the entity_id as a variable?

Example:

{% set x = 'switch.shellyplug_1' %}
{{ states[x].last_changed }}
1 Like

Yes, I was just going this direction. Thank you!

1 Like