Template Filter help

Hi,

I have several input_select objects which I use for my presence detection. Values can be Home, Just Left, Just Arrived, Away, Extended Away.

I want to count the ones which have either Home, Just Left or Just Arrived.

Right now my value_template reads as follows:

value_template: >-
                {{  (dict((states.input_select)|groupby('state'))['Home']|default([])|count +
                     dict((states.input_select)|groupby('state'))['Just Left']|default([])|count +
                     dict((states.input_select)|groupby('state'))['Just Arrived']|default([])|count) > 0
                }}

Is there an easier way to do this by first filtering only those input_select objects which have either attribute and then counting them rather then counting each individually and then adding them up?

I’m likely overcomplicating things because the above statement “works” but i feel it can be optimised :slight_smile:

Thanks

Would this do it?

{{ states.input_select | selectattr('state', 'in', 'Home,Just Left,Just Arrived') | list | count }}

Use a list of strings for the test involving in.

{{ states.input_select | selectattr('state', 'in', ['Home', 'Just Left', 'Just Arrived']) | list | count }}

Your version will match on any sub-string within 'Home,Just Left,Just Arrived'. In other words, it will match on “Arrived”, “Just”, “Left” or any other fragment.

1 Like

Good to know @123 (given the list of options wouldn’t have been a problem but if you’d only wanted ‘Just Arrived’ and exclude ‘Just Left’ I can see where it would have fallen down) - that’s my afternoon taken care of now tightening up my config!

Thank you both! really helpful

FWIW, I have always used a list with in (it can also be a tuple) and never a string like in your example. So I tried it on my test system like this:

{{ states.input_select | selectattr('state', 'in', 'off, None') | list }}

It worked; it reported all input_selects whose value is either “off” or “None”. However, it also reported an input_select whose value is “No” because it’s a sub-string of “None”. So, yes, it works but a little too well. :slightly_smiling_face:

1 Like