Are my templates wrong?

I noticed this on the Templating page

I’m not sure if my templates are correct or wrong. Can anyone tell? They are working fine.

If this is wrong, could you correct me? I’m using all my templates like this and want them to be as advised (count lights on, count radiators, covers) But i do want to choose wich specific entities to monitor.

{% set covers = [
states.cover.screen_voorzijde,
states.cover.screen_achterzijde,
states.cover.maestria_io,
states.cover.maestria_io_2
] %}

{{ covers | selectattr(‘state’, ‘eq’, ‘closed’) | list | count }} Screen(s) closed

{% set covers = [
states('cover.screen_voorzijde'),
states('cover.screen_achterzijde'),
states('cover.maestria_io'),
states('cover.maestria_io_2')
] %}

{{ covers | select('eq', 'closed') | list | count }} Screen(s) closed

This does the exact same thing as your template 99% of the time. Once in a while yours may break during startup because the entities you’re listing there aren’t ready. This version will not break in that 1% edge case.

Are all your templates wrong?

Hard to say. If you are ignoring that warning everywhere then probably most of your templates could benefit from a refactor according with that note to eliminate errors in edge cases. There are a few things that you can only do with the states.<entity_id> pattern so some may be correct as is. The most common one is using last_changed or last_updated in a template, you have to do states.<entity_id>.last_changed or states.<entity_id>.last_updated for that.

But for accessing the state or a value of an attribute you should do what that note says.

1 Like

If you wanna look at all covers (with no need to create a var with each one listed) you could do like this:

{{ states.cover | selectattr('state', 'eq', 'closed') | map(attribute='entity_id') | list | count  }} screen(s) closed

Thanks a lot! I’ll change them all.

Thank you! That is an option for some of my templates.

You can also use the expand function to do this:

{{ expand('cover.screen_voorzijde', 'cover.screen_achterzijde', 'cover.maestria_io', 'cover.maestria_io_2')
  | selectattr('state', 'eq', 'closed') | list | count }} Screen(s) closed

Cool, I understand the templating stuff much better now. Thanks.

1 Like