How to append matched sensor states in a list during iteration

Hi out there,
the title tells the hole story…

DOKU--Template_25%

i did read a lot, in ha-docs, too, but nothing to find…

i did try:

  1. do SensorDeadline.append(key)
  2. SensorDeadline.append(key)

but allways the same error:
Encountered unknown tag ‘SensorDeadLine’.

Please, is there a way to handle dynamik lists ?

Many thanks in advance!
So long
Pc

You need to define an empty list, before the for-loop, using namespace. You append an item to the list using the + operator.

Example

The following example copies items from list x into list y, one item at a time using a for-loop.

{% set x = ['cat', 'bat', 'rat'] %}
{% set ns = namespace(y = []) %}
{% for z in x %}
  {% set ns.y = ns.y + [z] %}
{% endfor %}
{{ ns.y }}

Hi,
thank you. You’re welcome.

Only for my information:
is there another way to do it ?

So long
Pc

Certain parts of Jinja2 aren’t supported by Home Assistant’s implementation of it. For example, the append method isn’t supported.

Currently, using the + operator is the most common way of appending one list to another.

The use of namespace is required to ensure the changes you make to the list inside the for-loop will exist outside the for-loop.

1 Like

[NO FURTHER INFORMTION]

THANK YOU.
I’ll make a note of this (append support) for me for the next WTH session :wink:

So long
Pc

My understanding is that some Jinja2 commands have been intentionally excluded (not merely overlooked) because they can cause memory management challenges. Or at least that’s how I recall it being explained.

Similar restrictions also exist for the python_script integration.

1 Like