Automation for binary sensor: to_state?

I copied this YAML from another post. My recollection is that it was working fine. It is retrieving the name of an entity that caused the trigger from a group.

service: notify.sendgridnotify
data:
  title: Leak Detected!
  message: |-
    {% for entity in trigger.to_state.attributes.entity_id %}
      {% if states(entity) == 'on' %}
        {{ state_attr(entity, 'friendly_name') }} has detected water.
      {% endif %}
    {% endfor %}

Now when it runs I receive this error message:

Error: Error rendering data template: UndefinedError: ‘dict object’ has no attribute ‘to_state’

Any suggestions on how to correct?

Thanks!

It you are testing this manually it skips the trigger (and conditions) so there are no trigger.to objects.

Test it by changing the state of one of the binary sensors in Developer Tools → states.

This is kind of a pointless template, there will only ever be one triggering entity. Even if two leak sensors go off “at once” it will be a race but only one of them will trigger first.

So it is equivalent to:

  message: >
        {{ trigger.to_state.name }} has detected water.

AWESOME! Thank you so much for the help. It now works as expected. And simpler is always better. This is the danger of copy/paste programming.

For the sake of those who may stumble on this q & a. The orginal code worked fine for a Group:

service: notify.sendgridnotify
data:
  title: Leak Detected!
  message: |-
    {% for entity in trigger.to_state.attributes.entity_id %}
      {% if states(entity) == 'on' %}
        {{ state_attr(entity, 'friendly_name') }} has detected water.
      {% endif %}
    {% endfor %}

and the suggestion worked perfectly for an entity:

  message: >
        {{ trigger.to_state.name }} has detected water.