How to use template in service_data?

In script.vacuum_clean_zone, you can reduce the size of the content template like this:

vacuum_clean_zone:
  alias: Pulisci zona
  sequence:
  - service: vacuum.send_command
    data_template:
      command: "{{command}}"
      entity_id: "{{entity_id}}"
      params:
        act: start
        content: >
            {% set rooms = [ ['kitchen', 0],
                             ['living', 2],
                             ['lunch', 10],
                             ['disimpegno', 3],
                             ['little_bathroom', 5],
                             ['bathroom', 4],
                             ['bedroom', 6],
                             ['little_bedroom', 9] ] %}
            {% set ns = namespace(x = '') %}
            {% for room in rooms if is_state('input_boolean.clean_' ~ room[0] ~ '_boolean', 'on') %}
                {% set ns.x = ns.x ~ room[1] ~ (',' if not loop.last else '') %}
            {% endfor %}
            {{ ns.x }}
        count: "{{count}}"
        type: "{{type}}"
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_kitchen_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_living_boolean 
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_lunch_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_disimpegno_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_little_bathroom_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_bathroom_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_bedroom_boolean
  - service: input_boolean.turn_off
    data:
       entity_id: input_boolean.clean_little_bedroom_boolean

How it works:

  • It defines a list called rooms where each item in the list is yet another list containing the room’s name and value.
  • It defines a global variable ns.x to store the selected room values.
  • It iterates through the rooms list but only for items whose corresponding input_boolean is on.
  • An eligible room has its value appended to ns.x. A comma is appended to the value but not if it’s the last value.
  • It reports the variable ns.x.

NOTE:
The tilde character (~) is used to indicate concatenation. The plus character (+) can be ambiguous because it can add numbers or, if one of the values is a string, concatenate them. Ideally, use tilde when you want concatenation and use plus when you want addition.

2 Likes