Counting matching states

It’s in the Jinja documentation:

http://jinja.pocoo.org/docs/dev/templates/

Under “Builtin Filters”

1 Like

Awesome. Gonna have a lot of refactoring beforeme. Thanks!

~Cheers

excuse me for replying in this old topic, but this topic is the closest I found for my problem.

About a week my counting sensor does not work anymore. First I used this example, found in this topic of floreplan from Smoculetz, in my configuration.yaml file and it worked fine for a few months.

   sensor:
      - platform: template
        sensors:
          number_of_lights_on:
            value_template: >-
                {% for state in states if ( 'light' in state.entity_id and state.domain in ['light','switch'] and state.state == 'on' ) -%}
                    {% if loop.last -%}
                    {{ loop.index - 1}}
                    {%- endif %}
                    {% else %}
                        0
                {%- endfor %}

Then I changed my hardware and thereby also changed the entities of all my lights. All the entities are still part of the lights in the configuration.yaml file. But the sensor doesn’t count the ‘on’ state anymore.
Afther surching I found this topic with the example of Danrspencer and I used it in the hope the sensor would work again:

sensor:
  - platform: template
    sensors: 
      number_of_lights_on: 
        value_template: >-
            {{ states.light
            | selectattr('state', 'eq', 'on')
            | rejectattr('attributes.all_lights')
            | list
            | count
            }}

But with no succes.

Both examples work fine in the template editor. The sensor won’t detect any state change of the lights. when I put (for example) 3 lights on and restart HA then the sensor shows 3. When I put them out, or others on, without restarting HA, the sensor don’t changes the count. It just remembers the last state before restarting HA.

I have searched the forum but can’t find any changes or update failures of this topic with the new HA release. So my knowledge and options for now are out. therfor my screem for help.

Can someone help me to find what I am doing wrong?