Count open doors of my car and set alarm flag

Hi all,
I am struggling with a template.

The expected result should be:

  • alarm flag if one of the doors is open
  • which doors are open
  • how many of the 4 doors are open

The code does not really work, because the counter will not be updated if a door is closed. Maybe somehone has an idea to simplify the code. It looks very complicated!

{% set hr=0 %}
{% set hl=0 %}
{% set vr=0 %}
{% set vl=0 %}
{% if (states("binary_sensor.cupra_born_door_rear_right_open_status"))=='on'%}
{{ 'hinten rechts'}}
{% set hr =1%}
{% elif (states("binary_sensor.cupra_born_door_rear_left_open_status"))=='on'%}
{{ 'hinten links'}}
{% set hl =1%}
{% elif (states("binary_sensor.cupra_born_door_rear_right_open_status"))=='on'%}
{{ 'vorne rechts'}}
{% set vr =1%}
{% elif (states("binary_sensor.cupra_born_door_front_left_open_status"))=='on'%}
{{ 'vorne links'}}
{% set vl =1%}
{% else %}
{{' alle zu'}}
{%endif%}
{{hr+hl+vr+vl}}/4 Türen geöffnet

Where did this code come from?

it was a first test in the template section and later on I will use this in a mushroom template card in order to display the status of the doors

I have tried to simplify, but this code is also not working. What is wrong?

{% set doors = {
    "binary_sensor.cupra_born_door_rear_right_open_status": "hinten rechts",
    "binary_sensor.cupra_born_door_rear_left_open_status": "hinten links",
    "binary_sensor.cupra_born_door_front_right_open_status": "vorne rechts",
    "binary_sensor.cupra_born_door_front_left_open_status": "vorne links"
} %}

{% set open_doors = doors | selectattr("states", "equalto", "off") | map("value") | list %}

{{ open_doors | join(", ") if open_doors | length > 0 else 'alle zu' }}

{{ open_doors | length }}/4 Türen geöffnet

…this looks a little bit better, I hope that this is the solution. If someone knows a better way, please let me know!

{% set doors = {
    "binary_sensor.cupra_born_door_rear_right_open_status": "hinten rechts",
    "binary_sensor.cupra_born_door_rear_left_open_status": "hinten links",
    "binary_sensor.cupra_born_door_front_right_open_status": "vorne rechts",
    "binary_sensor.cupra_born_door_front_left_open_status": "vorne links"
} %}

{% set ns = namespace(open_doors=[]) %}

{% for sensor, name in doors.items() %}
    {% if states(sensor) == 'on' %}
        {% set ns.open_doors = ns.open_doors + [name] %}
    {% endif %}
{% endfor %}

{{ ns.open_doors | join(", ") if ns.open_doors | length > 0 else 'alle Türen zu' }}

{{ ns.open_doors | length }}/{{ doors | length }} Türen geöffnet