Is it possible to loop though attributes?

EDIT: I have solved this (but see @pnbruckner’s better solution).

{%- for train in states.sensor if train.entity_id.endswith('next_train_to_abc') -%}
  {%- for attr in train.attributes %}

then access each one using loop.index

e.g.

states.sensor.next_train_to_wea.attributes.next_trains[loop.index].scheduled

I have several places where I loop through states in entities and act on them as appropriate but is it possible to loop through attributes?

I have a sensor which presents as follows:

states.sensor.next_train_to_abc.attributes.next_trains[0].scheduled
states.sensor.next_train_to_wea.attributes.next_trains[0].estimated
...
states.sensor.next_train_to_wea.attributes.next_trains[0].platform


states.sensor.next_train_to_wea.attributes.next_trains[1].scheduled
states.sensor.next_train_to_wea.attributes.next_trains[1].estimated
...
states.sensor.next_train_to_wea.attributes.next_trains[1].platform

and so on.

I would like to loop through next_trains.
Is this possible? I couldn’t find a syntax that worked.

Why don’t you just do something like:

{% for train in states.sensor.next_train_to_wea.attributes.next_trains') %}
   {{ train.scheduled }}
   {{ train.estimated }}
   {{ train.platform }}
{% endfor %}

Or maybe you want something like this:

{% for trains in states.sensor if trains.entity_id.endswith('next_train_to_abc') %}
  {% for train in trains.attributes.next_trains %}
     {{ train.scheduled }}
     {{ train.estimated }}
     {{ train.platform }}
  {% endfor %}
{% endfor %}

It was completely clear what you wanted, but basically, next_trains is a list, so just iterate over it.

1 Like

Thanks, whilst my solution works yours results in less code in the loop (your second example is what I was after).

The best part being that having found my solution and then seeing yours it has made obvious what is going on in more general terms.

1 Like