Why does this code no longer work?

I’ve been using this code for some time now and just noticed after 2022.6.2 that it is no longer working. Here is a ‘simple’ and ‘extended’ version, both pulled from the forums:

{% for state in states.automation | selectattr('attributes.last_triggered') | sort(attribute='attributes.last_triggered', reverse=true) -%}
{{ state.attributes.last_triggered }} : {{ state.name }}
{% endfor %}

and

{% for state in states.automation
   |selectattr('attributes.last_triggered')
   |sort(attribute='attributes.last_triggered', reverse=true) -%}
  {%- set t = now() - state.attributes.last_triggered -%}
  {%- set days = t.days if t.days > 0 else '0' -%}
  {%- set hrs = t.seconds//3600 %}
  {%- set hrs = hrs if hrs > 0 else '0' -%}
  |{{days}}|{{hrs}}|{{(t.seconds//60)%60}}||_{{state.name}}_|
{% endfor %}

Have I missed something in the recent breaking changes or is this a new issue?

You need to add a filter to include only entities where last_triggered is defined:

{% for state in states.automation
   | selectattr('attributes.last_triggered', 'defined')
   | selectattr('attributes.last_triggered')
   | sort(attribute='attributes.last_triggered', reverse=true) -%}
  {%- set t = now() - state.attributes.last_triggered -%}
  {%- set days = t.days if t.days > 0 else '0' -%}
  {%- set hrs = t.seconds//3600 %}
  {%- set hrs = hrs if hrs > 0 else '0' -%}
  |{{days}}|{{hrs}}|{{(t.seconds//60)%60}}||_{{state.name}}_|
{% endfor %}

@Didgeridrew
Thank you. That worked. Did I miss this in the breaking changes? I usually pay pretty close attention to thinks that might impact my system, but this one certainly got under my radar. Thanks again for the correct solution and a prompt reply.

It broke because in 2021.4 HA started logging a warning for references to undefined variables in templates. See here in the release notes:

This was planned to go from a warning to an error in 2021.10. Clearly that date was extended but in 2022.6 this warning finally became an error. If you expand the “Template filter/function defaults” section in breaking changes, I believe that PR is what made yours fail as well.

Although it appears it doesn’t specifically mention that the undefined variables warning became an error as well, it just talks about the filters with a default option. So could submit a documentation bug on that. But every time that template rendered for over a year now a warning was logged telling you it was doing something wrong. So this particular breaking change shouldn’t have come as a surprise.

That is why Drew’s addition above fixes it. By first doing | selectattr('attributes.last_triggered', 'defined') before doing | selectattr('attributes.last_triggered') you strip out the results that don’t have that attribute. Those ones cause an “undefined variable” error in the second filter.