Decide which service to call using a template

In the official docs it says that a template can be used to decide which service to call. It also says that the docs is for Lovelace. But when I try it with the following code:

type: entities
entities:
  - entity: camera.au_terrasse_kamera
    secondary_info: last-changed
    tap_action:
      action: call-service
      service: |
        {% if is_state('sensor.au_terrasse_kamera_wiedergabesensor', 'False') %}
          camera.turn_on
        {% else %}
          camera.turn_off
        {% endif %}
      target:
        entity_id: camera.au_terrasse_kamera

I only get an error message “Failed to call service {% if is_state(‘sensor/au_terrasse_kamera_wiedergabesensor’, ‘False’) %} camera. Unable to find service {% if is_state(‘sensor.au_terrasse_kamera_wiedergabesensor’, ‘false’) %} camera”

What am I doing wrong?

Replace

     service: |

by

     service: >

In automations and scripts, not in a standard Lovelace Card.


Make a script to turn on/off the camera depending on the state of the sensor.

script:
  au_terrasse_kamera:
    alias: Au Terrasse Kamera
    sequence:
      - service: "camera.turn_{{ 'on' if is_state('sensor.au_terrasse_kamera_wiedergabesensor', 'False') else 'off' }}"
        target:
          entity_id: camera.au_terrasse_kamera

Change tap-action to this:

type: entities
entities:
  - entity: camera.au_terrasse_kamera
    secondary_info: last-changed
    tap_action:
      action: call-service
      service: script.au_terrasse_kamera
1 Like

Actually I typed “>” but after saving it always gets changed to “|”.

Ah, I think the docs are a bit misleading then.

But a service can also be called from a script, a Lovelace dashboard or via voice command devices such as Amazon Echo.

The configuration options to call a configuration are the same between all integrations and are described on this page.

As it is not mentioned on that page anywhere that templates don’t work for Lovelace cards I’ll file a PR to include that information later.

Your suggested way works fine, thank you for that.

As I have 7 cameras, I made it a bit more generic:

Dashboard:

type: entities
entities:
  - entity: camera.au_terrasse_kamera
    secondary_info: last-changed
    tap_action:
      action: call-service
      service: script.kamera_toggle_2
      service_data:
        kamera: camera.au_terrasse_kamera
        wiedergabesensor: binary_sensor.au_terrasse_kamera_wiedergabesensor

Script:

alias: Kamera Toggle 2
sequence:
  - service: camera.turn_{{ 'on' if is_state(wiedergabesensor, 'False') else 'off' }}
    target:
      entity_id: '{{ kamera }}'
mode: single

Possibly but a “Lovelace dashboard” is not a “Lovelace card”. At this time, the only standard Lovelace card that supports templating is the Markdown card; all others do not. There are a few custom Lovelace cards that do support templates.

Good idea. :+1:

1 Like