Possible to iterate in a service script to generate a section of YAML?

I’d like to generate YAML to show open doors on an ePaper display. It would be great to be able to iterate over my external door group and show the ones that are open without duplicating code for each door, and having to do more each time I add in another sensor. Is it possible at all? The way I’m trying to do it seems to be a non-starter:

service: open_epaper_link.drawcustom
target:
  entity_id:
    - open_epaper_link.0000021BA6803B15
data:
  background: white
  dry-run: true
  payload: >-
    {%- for openDoor in expand('binary_sensor.external_doors') | selectattr('state','eq','on') -%}
    - type: text
      value: {{openDoor.name}}
      font: ppb.ttf
      x: 0
      y: 10
      size: 10
      color: black
    {% endfor %}

I have to say I don’t really understand when to use -, >-, |- but whatever I put at the top where payload starts results in an error, even if I take out the for loop.

Using a Jinja for loop to generate YAML can be a recipe for frustration. As you have set it up, the output isn’t interpreted as actual YAML, just a YAML-shaped string.

Since YAML is kind of a subset of json, and the template engine can output json objects, you should be able to use that to set your service data.

service: open_epaper_link.drawcustom
target:
  entity_id:
    - open_epaper_link.0000021BA6803B15
data: |
    {% set ns = namespace(doors=[]) %}
    {%- for openDoor in expand('binary_sensor.external_doors') | selectattr('state','eq','on') -%}
    {% set ns.doors = ns.doors + [ { "type": "text", "value": openDoor.name, "font": "ppb.ttf", "x": 0, "y": 10, "size": 10, "color": "black"} ] %}
    {% endfor %}
    {{ {"background": "white",
    "dry-run": "true",
    "payload": ns.doors } }}    

The first line sets up a namespace to allow us to output a true list from the loop to use as the value for payload.

There are technical differences between | and >, but in HA you can pretty much use them interchangeably.

1 Like

Thanks Didgeridrew. That does look kind of frustrating though! Is this something that people would use Node Red for instead?

I am not the person to ask about why or how people might use NodeRed… :grin:

1 Like