Help with Templating and Unwanted Output

I’m trying to create a script that will use Alexa tts to announce a list of open doors. So i’m wanting to make a template that looks at each door and if it’s open, add it to a string. I want this to sound natural so if one door is open it’ll say ‘x door is open’, if two doors are open it’s ‘the x door and y door are open’ and finally if it’s more doors it’ll say ‘x door, y door and z door are open’.

My approach to this was to be check each door in turn, if open (sensor on) add it to an array (list) and then evaluate how many values are in that array to create the final string with proper grammar.

My first hurdle was the fact that for security reasons you can’t use array.append(), but there is a workaround which is in my template below. However, it’s outputting in developer tools the array as i join it together, which is going to mess up my output.

{%- set data = namespace(opendoorsensors=[]) -%}

{% if is_state('binary_sensor.front_door_sensor','on') %}
{% set data2 = namespace(tempList = ["Front Door"]) %}
{% set data.opendoorsensors = data.opendoorsensors + data2.tempList %}
{{ data.opendoorsensors | join(",") }}
{% endif %}

{% if is_state('binary_sensor.back_door_sensor','on') %}
{% set data2 = namespace(tempList = ["Back Door"]) %}
{% set data.opendoorsensors = data.opendoorsensors + data2.tempList %}
{{ data.opendoorsensors | join(",") }}
{% endif %}

{{data.opendoorsensors|length}}

Outputs:

Front Door





Front Door,Back Door


2

If I change the brackets on the line with a join to {% %} it gives me an error - so how can I accomplish this without the unwanted output? I think this is just down to me not understanding the syntax/limitations of templating jinja.

Finally - if i’m approaching this in an entirely overcomplicated and daft way please let me know!

You might want to take a look at-

You will need to create a group of your doors/windows first.

1 Like

Ooh that looks much better - thank you !