Variable to count items in template

I would like to build an Alexa intent to give the number of windows opened. I can’t find the way yo increment a variable in a template. I am using “set counter = counter +1”. It seems to work for the first one but as soon as I add another one, I have an error.
The script is below:

  CheckWindows:
    speech:
      text: >
        {% set counter = 0 %}
        {% set counter = counter + 1 if is_state("binary_sensor.dining_room_window", "on") %}
        {% set counter = counter + 1 if is_state("binary_sensor.kitchen_window", "on") %}
        {% if int(counter) > 0 %}
            {{ counter }} windows opened
        {% else %}
            No windows opened
        {% endif %}
    card:
      type: simple
      title: Windows check
      content: >
          Windows opened

Try this:


              {%- set e = expand(states.binary_sensor)
                 |selectattr('attributes.device_class', 'defined') 
                 |selectattr('attributes.device_class', 'in', ['opening', 'window'])
                 |selectattr('state', 'eq', 'on')
                 |list
                 |count %}

              {{ e ~ ' Fenster offen'}}

(|selectattr('attributes.device_class', 'in', ['opening', 'window']) depends on which device class is used)

Wow! It works great, thank you!
I see the logic behind your code, a lot more elegant and effective than mine :slight_smile:

Small addition, plural:


            {{ e ~ ' window' }}{{ 's' if e > 1 else ' ' }}