Hellberg
(Fredrik)
May 23, 2023, 3:45pm
1
All of a sudden my card that shows how many open windows i have, gives me a number zero. Before the update i shows nothing (when nothing is open).
What shall i change in the code?
{% set lights = [
states.binary_sensor.openclose_28,
states.binary_sensor.openclose_29,
states.binary_sensor.openclose_36,
] %}
{{ lights | selectattr(‘state’,‘eq’,‘on’) | list | count }}
tom_l
May 23, 2023, 6:07pm
2
Please format your code correctly for the forum in future .
Try this
{{ lights | selectattr(‘state’,‘eq’,‘on’) | list | count | int(0) }}
If the count result can’t be converted to an integer it will be replaced with the specified default, zero.
Hellberg
(Fredrik)
May 23, 2023, 7:24pm
3
Sorry. Made the post in a hurry. Next time i will format in correctly.
I tested your example but it still shows a “0”.
tom_l
May 23, 2023, 7:27pm
4
Oh sorry I read that back to front. I thought you wanted 0. For nothing when zero try this:
{{ lights | selectattr(‘state’,‘eq’,‘on’) | list | count | replace('0', '') }}
It may or may not work. There have been some strict changes to sensors, they can now only be string OR numeric types . Not both.
If you have a unit_of_measurement defined for the sensor you will have to remove it.
petro
(Petro)
May 24, 2023, 11:38am
6
I’m not sure how that works. Count returns an int and you’re attempting to replace a value in a string. Unless the jinja replace has some magical powers, I wouldn’t expect that to work.
An availability template would work the best for this case IMO
tom_l
May 24, 2023, 11:58am
7
I may be abusing it but I did test replacing an int in the template editor.
An availability template won’t work. They want an empty string as the result, not unavailable
.
petro
(Petro)
May 24, 2023, 12:17pm
8
An empty string will show up as unavailable
tom_l
May 24, 2023, 12:23pm
9
It didn’t in the template editor and OP is happy so
123
(Taras)
May 24, 2023, 2:05pm
10
FWIW, I tested the following template in the Template Editor and, like you said, it produces an empty string (like Hellberg wants).
{{ 0 | replace('0', '') }}
However, if the count is 10
then the template will report 1
(because replace
replaces any instance of 0
).
{{ 10 | replace('0', '') }}
To avoid indiscriminately replacing zero with nothing, the template should use regex_replace
. For example, this correctly reports 10
.
{{ 10 | regex_replace('^0', '') }}
For Hellberg’s purposes:
{{ lights | selectattr('state','eq','on') | list | count | regex_replace('^0', '') }}
1 Like