Markdown Card For Loop

I’m having a problem getting the length of a loop to show one time. I’m guessing it’s a syntax issue. Here’s my code:

{% for l in config.entities %}
  {% if ("state.l.entity", 'on') %} 
    Lights on: {{ loop.length }}
  {% endif %}
{% endfor %}

{% for l in config.entities if ("state.l.entity", 'on') %}
  {{ l.name }}
{%- endfor %}

38 PM

Why is the length repeating? Sorry, first time Python, and new to Home Assistant. I read the Jinja and Markdown Card docs and still can’t seem to figure it out. Thanks to anyone who can point me in the right direction.

Your lights on needs to be outside

Like this?


{% for l in config.entities %}
  {% if ("state.l.entity", 'on') %} 
  {% endif %}
  Lights on: {{ loop.length }}
{% endfor %}

Tried it, but it returns the same. Also tried outside the for loop, but that breaks it.

Well you would normally

Initialize a variable to 0
Enter the loop
Perform validation
if validation is true
Add 1 to the variable
End of validation
End of loop
Print results

Thanks for your help. I really appreciate it. Unfortunately still not able to get it.

{% set count = 0 %}
{% for l in config.entities %}
  {% if ("state.l.entity", 'on') %}
    {% set count = count + 1 %} 
  {% endif %} 
{% endfor %}

This results in 0 printed once, which makes sense because count is outside of the scope.

{% for l in config.entities %}
  {% set count = 0 %}
  {% if ("state.l.entity", 'on') %}
    {% set count = count + 1 %} 
  {% endif %} 
  {{ count }}
{% endfor %}

This results in 1 printed as many times as looped through.

No need for a loop to count lights that are on.
Take a look in this topic for multiple examples.

Lights that are on:

{{ states['light']  | selectattr('state','eq', 'on') | list | count }}

I figured there would be a better way. Saving that link, it’s super helpful. Thank you!