Combination of service_template and data_template fails

Hello,

my objective is to use 3 soundtouch speakers to broadcast messages via the tts command. In an automation I generate fields for the number of devices switched on, the status of the spotify player and lists for switched on/off devices. I pass those field to a script. After the tts sequence, I want to switch off those media_players, which were not on at the beginning (mediaplayer_off). This works fine with

service_template: |-
{% if count_off != 0 %}
media_player.turn_off
{% endif %}
data:
entity_id: ‘{{mediaplayer_off}}’

unless all media_players are on. Then mediaplayer_off is an empty list. I also restart spotify, if the spotify player played before with the following sequence:

service_template: |-
{% if spotify_on == true %}
media_player.media_play_pause
{% endif %}
data:
entity_id: media_player.spotify_player

If now all 3 media_players (soundtouch) are on I simply want to combine both sequences into

service_template: |-
{% if count_off != 0 %}
media_player.turn_off
{% elif spotify_on == true %}
media_player.media_play_pause
{% endif %}
data_template:
entity_id: |-
{% if count_off != 0 %}
‘{{mediaplayer_off}}’
{% elif spotify_on == true %}
media_player.spotify_player
{% endif %}

but this sequence is not executed. I tried the sequence in the developer_tools → templates and got in my opinion the right output, which would restart spotify, when all 3 mediaplayers (soundtouch) are on. Any idea, why the combination of service_template and data_template is not working?

Regards,

Volker

first you need to properly format your posted code blocks so re more readable. add three backticks (```) before and after the code blocks.

second “service_template” and data_template" are no longer used. just use “service” and “data” and HA will be smart enough to know if you use a template.

I am not that familiar with the exact syntax in the forum. I therefore upload the screenshots for the separate blocks

and the combined sequence mentioned in the original message:

use choose: Script Syntax - Home Assistant

Thank you! That helped with structuring the code. The error was eventually in evaluating and passing on the fields variables.

I recommend you take a moment to read the forum’s FAQ.

FWIW, it’s not mandatory to use choose but it does make it easier because the template logic you created has loopholes that can cause errors. For example, what happens if count_off is zero or spotify_on is false? The template’s if-elif fails to handle those situations so the template produces nothing … and that’s not a valid service call.

Thank you! Also that was very useful. I am getting on the learning curve.

1 Like

You’re welcome!

NOTE
Only one post in the entire thread can be marked with the Solution tag. You should mark Mati24’s post (as you originally did) with the Solution tag, not mine, because you are using it’s suggestion to fix the problem.