#jinja question re sorting on state value

1 messages · Page 1 of 1 (latest)

carmine creek
#

I'm trying to use something like the below, but sorting the rows based on state (which is the number of days until the persons birthday, but it's a string value not an int).
How do I cast the state in the sort so the rows are ordered correctly?
e.g. I'm currently getting rows in the order of '108', '112', '18', '1', '208', '20' which is not what anyone would expect.

{%- for state in states.birthdays|sort(attribute="state") -%}
  {{{ "state": state.state,"name": state_attr(state.entity_id, "friendly_name"), "secondary": "Will be " ~ state_attr(state.entity_id, "age_at_next_birthday") ~ ", born " ~ state_attr(state.entity_id, "date_of_birth"), "icon": "mdi:cake-layered", "type": "custom:template-entity-row" }}} 
  ,
{%- endfor -%}

Thanks!

EDIT: I should say this is coming from the ha-birthdays integration I installed thru hacs https://github.com/Miicroo/ha-birthdays

GitHub

Birthday integration for HomeAssistant. Contribute to Miicroo/ha-birthdays development by creating an account on GitHub.

minor badge
#

all states are strings, the only way to do this correctly is to first create a list with mappings and then sort it

#

unless the date of birth attribute is in YYYY-MM-DD format, then you can sort on that

#

heck, if it's in MM-DD-YYYY format you can also sort on it, as the year is not relevant for the number of days until the next birthday

carmine creek
#

ah ok, I thought there might be some way of telling sort to treat the value as numeric. thanks - I'll try to find some other way

minor badge
#

what is the date format of that attribute?

carmine creek
#

it's standard iso 8601, to the day. so yyyy-mm-dd

minor badge
#

hmm, then sorting on it won't help

#
{% set ns = namespace(bdays=[]) %}
{% for s in states.birthdays %}
  {% set ns.bdays = ns.bdays + [dict(name=s.name, days=s.state|int, age=s.attributes.age_at_next_birthday, born=s.attributes.date_of_birth)] %}
{% endfor %}
{% for bd in ns.bdays | sort(attribute=days) %}
  {{ {"state": bd.days, "name": bd.name, "secondary": "Will be " ~ bd.age ~ ", born " ~ bd.born, "icon": "mdi:cake-layered", "type": "custom:template-entity-row"} }} 
  ,
{% endfor %}
#

something like this should work