Please help me with some syntax. I want to insert conditions around some entity ids in the script below. For each media player (office, study, bedroom) I have an input Boolean (on / off). I would like to use the input_booleans to include/uninclude the media_player lines in the entity id entry below. I don’t know how to proceed:
Sorry to say, but this will be difficult purely because you are dealing with a list. Templating is possible with a list but you’d need to template each line due to the limitations of Jinja (Template code language). The problem with this is that your list is unique. You want this input boolean to include or not include media players. This could put you in a catch 22. I’m not sure you can provide a list in yaml without an item in it. For example, if have office and bedroom on, your list would be ['office', '', 'bedroom]. This could cause problems. If you want to try it, here’s the service w/ Jinja:
- service: media_player.sonos_unjoin
data_template:
entity_id:
- "{{ 'media_player.office' if is_state('input_boolean.media_player_office','on') else '' }}"
- "{{ 'media_player.study' if is_state('input_boolean.media_player_study','on') else '' }}"
- "{{ 'media_player.bedroom' if is_state('input_boolean.media_player_bedroom','on') else '' }}"
I do not know what will happen if you send a list with various items empty. It could cause an error in the log. It could also be ignored and do nothing.
If you are getting errors with the above template during execution, you need to move to a different model. At that point you should probably go with a python script because basic templates and conditions will not get you where you want to be.
Again, this is all because you need to output a list for entity_id. If it was a single value and not a list, it wouldn’t be this complicated. The limitations come from Jinja, which is what templates are built off of. Jinja only outputs single strings. It’s impossible to take a for loop in jinja and turn it into a list meant for yaml.
You’d get an error if all 3 input_booleans were off, you’d also get 3 errors instead of 1. Also, you’d get some crazyness when only 1 is on because the service would unjoin the same device 3 times.
I had to add the “service:” to line 6, but otherwise based on your example. I couldn’t get to be acceptable to Home Assistant until I added “Service:” so I took a shot.
I haven’t yet tried the second portion of your suggestion where the script is called. I added the code above to my script.yaml, and checked the config and got the error as I have shown.