Script with if then logic

Hi all,

I am trying to create a script with logic. I want to turn the DVD player on when I turn on my TV, if the DVD player is currently off. In my scripts I have the following, however I cant get the syntax of the service_template right. Any help would be much appreciated.

 tvon: 
     sequence:
     - service_template: >
       {%- if is_state('device_tracker.dvd_family', 'away') -%}
         - service:  script.turndvdon
       {%- endif -%}   
   - service:  script.turntvon

Just a guess, but I don’t think you can put yaml inside of templates. I think the templates can only be inside of yaml values. So (if I’m right, which maybe I’m not), you have to put the template stuff inside the “service” section, or structure this in some other way.

Im not sure exactly what you mean, could you please give me an example?

After looking into this a bit, my understanding was wrong. Judging from what I see at https://home-assistant.io/docs/scripts/service-calls/ , you don’t want the “-service” under “-service_template” at all: you have to pick one or the other. Also, you want the value to be a service, such as script.turn_on or script.turn_off. script.turndvdon looks like a specific script, which is an entity.

I think you might want something more like:

sequence:
  - service: script.turn_on
    data_template:
      entity_id: >
        {% if is_state('device_tracker.dvd_family', 'away') %}
          script.turndvdon
        {% else %}
          script.donothing
        {% endif %}

Maybe there are better alternatives (that don’t require a script that does nothing).

1 Like

Thankyou I will give this a try. Appreciate your time.