Templating with objects instead of strings

I would like to do something like this:

  action:
    - service: notify.home_group
      data_template:
        message: "Motion sensor fired: *{{states.binary_sensor.foscam_motion.attributes.camera_name}}*"
        data: >
          {% if (states.binary_sensor.foscam_motion.attributes.file_type == 'photo') %}
          photo:
            file: "{{states.binary_sensor.foscam_motion.attributes.file_path}}"
            caption: "Motion sensor fired: {{states.binary_sensor.foscam_motion.attributes.camera_name}}"
            timeout: 30
          {% else %}
          document:
            file: "{{states.binary_sensor.foscam_motion.attributes.file_path}}"
            caption: "Motion sensor fired: {{states.binary_sensor.foscam_motion.attributes.camera_name}}"
            timeout: 120
          {% endif %}

But when automation is executed, I’m receiving this error in log:
Invalid service data for notify.home_group: expected dict for dictionary value @ data['data']. Got 'document:\n file: "/home/pi/ftp/cam_01/mi.jpg"\n caption: "Motion sensor fired: cam_01"\n timeout: 120'

Can I convert the string to a dict?

I ended up creating one script per action:

send_photo:
  sequence:
    - service_template: notify.{{receiver}}
      data_template:
        message: '{{caption}}'
        data:
          photo:
            file: '{{file}}'
            caption: '{{caption}}'
            timeout: 30

send_document:
  sequence:
    - service_template: notify.{{receiver}}
      data_template:
        message: '{{caption}}'
        data:
          document:
            file: '{{file}}'
            caption: '{{caption}}'
            timeout: 120

So automation now is:

  action:
    service_template: >
      {% if (states.binary_sensor.foscam_motion.attributes.file_type == 'photo') %}
        script.send_photo
      {% else %}
        script.send_document
      {% endif %}
    data_template:
      receiver: 'home_group'
      file: '{{states.binary_sensor.foscam_motion.attributes.file_path}}'
      caption: 'Motion sensor fired: {{states.binary_sensor.foscam_motion.attributes.camera_name}}'

I don’t think you can do that. You’d probably be better off with 2 separate automations and use a condition, one where file_type is a photo and the other when it’s not a photo.

1 Like

Thank you! @Jer78