Template binary sensor is not created

Im trying to create a binary_sensor that is equal with the newest value of a pair of two binary_sensors.

I placed this one under template: include …

- binary_sensor:
    - name: "Linkes Fenster (Spitzboden)"
      unique_id: binary_sensor.spitzboden_kontaktsensor_fenster_links_status
      device_class: "window"
      state: >
        {% if as_timestamp(states.binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status.last_changed) >as_timestamp(states.binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status.last_changed) %}
        {{states('binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status')}}
        {% else %}
        {{states('binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status')}}
        {% endif %}

Every other template sensor is working.

Where is my mistake? Thank you for your help.

On startup these may not exist and you need to account for that.

- binary_sensor:
    - name: "Linkes Fenster (Spitzboden)"
      unique_id: binary_sensor.spitzboden_kontaktsensor_fenster_links_status
      device_class: "window"
      state: >
        {% set link1 = states.binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status %}
        {% set link2 = states.binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status %}
        {% if not link1 and not link2 %}
          None
        {% elif link1.last_changed > link2.last_changed %}
          {{ link1.state }}
        {% else %}
          {{ link2.state }}
        {% endif %}

Thank you for your reply. Obviously my attempt seemed to work as expected but the problem is, that the entity id created is not the unique id, but the one which is derived from the name, in this case “binary_sensor.linkes_fenster_spitzboden”. Is this the expected behavior?

That is expected. The object_id is pulled from a sluggified name. Unique_id simply lets you adjust settings in the UI.

Trigger-based version, saves messing with timestamps:

template:
  - trigger:
      - platform: state
        entity_id:
          - binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status         - 
          - binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status
        to:
          - 'on'
          - 'off'
    binary_sensor:
      - name: "Linkes Fenster (Spitzboden)"
        state: "{{ trigger.to_state.state }}"

Great idea, but how do i initialize it? The value is set when the first change is happening?!

Yes, it will be unknown until the first sensor changes state.