Nested variable in template

Hi there:
I am trying to do the following:
I need to loop over all sensors states and, for those with a specific string in their entity_id, I need to get the state and some other attributes.
(FYI My devices names are standardize )
If I try this:

{% for state in states -%}
    {% if (state.entity_id.split("_")[2]) == 'whatever' %}
        {{states('{{state.entity_id}}')}}
    {% endif %}
{%- endfor %}

I just get unknown for every device although I know that the {{state.entity_id}} is properly converted (just put it there and it returns the entity_id for each device entering the if block). If I check each one with its own entity_id I get a proper state reply.
Any suggestion?
Thanks a lot.

SOLVED:
Really, really stupid…
{{states(state.entity_id)}}

I can guarantee you are not the first to make this mistake. :wink:

BTW, if all the entities that match are sensors (i.e., they all start with ‘sensor.’), then you can make this slightly more efficient by changing:

 {% for state in states -%}

to:

{% for state in states.sensor -%}

The first will loop over every state in the state machine, whereas the second will only loop over the states from the sensor domain.

Thanks mate!
BTW, I was hoping I could automatically get the last_updated from the zwave smartplug linked to each of those devices with something like this
{{ states.zwave.smart_plug_{{state.entity_id.split("_")[3]}}.last_updated }}

but it doesn’t seem to work (although states.zwave.smart_plug{{state.entity_id.split("")[3]}} creates the proper string)
Any idea how to do that?

Kind of the same issue as above – you can’t use a template inside a template. But you can do something like this:

{{ states.zwave["smart_plug_"~state.entity_id.split("_")[3]].last_updated }}

Super cool. Thanks a lot.
Important question: I’ve been googling but I can’t find a place where that kind of info is properly explained… Any suggestion?
I mean. I haven’t seen any zwave["smart_plug"~_ notation anywhere,

It’s probably scattered about a bit.

An attribute (especially in Jinja) can be accessed two ways: X.Y, or X['Y']. The former is more common, and the latter is usually used when the attribute name starts with a digit. (E.g., you can’t do X.1, so you have to do X['1'].) But the latter comes in handy for this sort of thing, too.

The tilda (~) operator is documented in the Jinja docs. It takes its two operands, converts them to strings if necessary, and then concatenates them. In this case you could have just used +, but in Jinja ~ is preferred.

Basically, you just have to read the docs. :slight_smile: This is probably the best place to start.

1 Like