Add foreach loop in script

I think it would be useful to add foreach as a new type of loop to repeat, as it is not always easy/possible/nice to do it using repeat.index.

Additional related ideas:

  • Saving current value in repeat.value
  • Iterating over arrays created using jinja template
    (e.g. {{ state_attr('group.all_devices', 'entity_id') }})

Calling @pnbruckner (creator of repeat action)

1 Like

why not make life easier? Use Node Red. You can write functions in JavaScript.

I don’t need NR, I can do everything in HA. If I want to write code I use built-in python script.

2 Likes

Could you give an example of how it could be used? Maybe provide some pseudo-code.

Another example use case:

My idea was to use it to call the same service with increasing delays between calls. There are a lot of potential uses :slight_smile:

A draft PR has been created. Still need to create tests and update docs.

1 Like

Incredibly annoying that this was rejected. It’s exactly what I need for a few tasks. To work around this I end up having to generate lots of ugly code using ansible’s jinja2 templating to write homeassistant jinja2 templating code.

I’ve opened up a PR to add it here:

5 Likes

Thanks @frenck!

2 Likes

Marked it as the solution, as it has been merged. Will be part of the 2022.5 release.

2 Likes