Template give me a number suddenly

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 = [
] %}
{{ lights | selectattr(‘state’,‘eq’,‘on’) | list | count }}

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.

Sorry. Made the post in a hurry. Next time i will format in correctly.
I tested your example but it still shows a “0”.

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.

That did it. Thanks!

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

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.

An empty string will show up as unavailable

It didn’t in the template editor and OP is happy so :man_shrugging:

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