Template in template: how to get "last_changed" for dynamically selected sensor

There is a sensor, let it be "sun.sun".
Now I need to get a "last_changed" value:

{{ states.sun.sun.last_changed }}

How to acquire the "last_changed" value if the sensor’s entity_id is defined as a “string”?
I need something like this which is not allowed:

{% set SENSOR_NAME = "sun.sun" %}
{{ states.{{SENSOR_NAME}}.last_changed }}

I managed to solve it, but only for some particular domain:

{{ states.sun['sun'].last_changed }}

So, for some "device_tracker" it will be:

{% set SENSOR_NAME = "XXXXXXXXX" %}
{{states.device_tracker[SENSOR_NAME].last_changed}}

or even this (if the string initially includes a domain):

{% set SENSOR_NAME = "device_tracker.XXXXXXXXX" %}
{% set SENSOR_NAME = SENSOR_NAME.split('.')[1] %}
{{states.device_tracker[SENSOR_NAME].last_changed}}

Is there any other universal solution for ANY domain?

What you arrived at should work everywhere, so I’m not following what more you’re looking for. Other options are .get("foo bar") or |attribute("foo bar"), and should be equivalent to ["foo bar"] as a way to index using a string, including one that has spaces or special characters in it.

The main task is:

  1. There is a decluttering template which has an input variable - "SENSOR".
  2. The decluttering template includes displaying a "last-changed" value for the "SENSOR" - in the manner that needs using things like (example for "sun.sun"):
LAST_CHANGED = states.sun.sun.last_changed
relative_time(strptime(LAST_CHANGED,"%H:%M:%S %d/%m/%Y"))

I mean that I cannot just specify something like "secondary_info: last-changed", I have to form it by myself since that "last-changed" value must be displayed in some special place.
3. So I need a method to form that "states.sun.sun.last_changed" expression - not just for "sun.sun" but for any "SENSOR" (which could be of any domain).

Could you give me some examples?

You need to split the entity string as you mentioned earlier, but here are some examples:

{{ states.sun['sun'].last_changed }}
{{ states.switch['fr_table_lamp'].last_changed }}
{{ states['switch']['fr_table_lamp'].last_changed }}
2 Likes

I see your point!

{% set SENSOR_NAME = "device_tracker.life360_mama" %}
{% set DOMAIN = SENSOR_NAME.split('.')[0] %}
{% set SENSOR_NAME = SENSOR_NAME.split('.')[1] %}
{{states[DOMAIN][SENSOR_NAME].last_changed}}

Great! Thank you very much!

1 Like

Can you please share all the code you have for this last changed monitoring?