I’m trying to create a count of entities that contain the string “node_status” in the object_id. I’m then going to use that value in another part of the same template in a sensor.
Right now I’m manually creating a group for entities and counting the members of the group. But I’d like to not need to add members to the group when I add other entities and just automatically count them since they all have “node_status” in the object_id.
The original template using the group that works is:
{% set total = (state_attr('group.zwavejs_devices','entity_id') | count) %}
{% set dead = expand('group.zwavejs_devices')|selectattr('state', 'in', 'dead, unavailable, unknown')|map(attribute='entity_id') | list | count %}
{{ total - dead }}/{{ total }}
I can get a total count of entities using this in the template editor:
{% for state in states if (state.entity_id.find("node_status") | int>=0) %}
{% if loop.first %}
{{loop.length}}
{% endif %}
{% endfor %}
it gives me a result of 29.
but I can’t use the count outside of the for loop and then use it to get the “total” in the above template.
I tried the following but it doesn’t return anything (no errors or complaints in the template editor):
{% set ns = namespace(count=0) %}
{% for state in states %}
{% if (state.entity_id.find("node_status") | int>=0) %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count }}
I admit I have really no clue when it comes to using “namespace”.
I’ve looked in the forums for examples and used them to come up with the template above.
And I’ve looked in the jinja2 docs for “namespace” usage but it’s pretty limited and it looks like what I’m doing should work.
Any idea where I’m going wrong?