If you sort sensor values or attributes with the “sort” filter, they get sorted by their ASCII value. But if you have numbers, the result ist not what you want:
{{ ["5","1","31","23","9","22","11"]|sort }}
gives you [‘1’, ‘11’, ‘22’, ‘23’, ‘31’, ‘5’, ‘9’]. So if you sort for example battery sensors, the list is not in the order you want it. So I developed a “natsort” filter. “natsort” splits text and numbers and sorts the numbers separate from the text.
So
{{ ["5","1","31","23","9","22","11"]|natsort }}
gives you [‘1’, ‘5’, ‘9’, ‘11’, ‘22’, ‘23’, ‘31’].
Another example for testing: battery values:
{{ states.sensor| selectattr('attributes.device_class', 'defined')|selectattr('attributes.device_class', 'eq','battery')|natsort(attribute="state")|list|join("\n\n") }}
I would like to make a change request to helpers/template.py if this function is desired.
For this, it is also necessary that HA installs the natsort module (dependency). How is this achieved?