Template sensor fails to update

I’ve used the template editor to create a template resulting in a correct value as seen in the Result window.
But when I paste the exact same template into Helpers → Template creating a named sensor, it always shows the value 0 (zero) when I check the entity value.
(I’ve tried creating this in configuration.yaml as well, but to no avail)
Why does this template evaluate correctly in the editor, but evaluates to 0 (zero) everywhere else I try to use it?

{% set hours_delay = two_days.index(two_days | select('<=', current) | first) if two_days | select('<=', current) | first is defined else -1 %}

N.B. Observe that I’ve declared/defined/created all the variables used, elsewhere. just didn’t see any reason to include it here.
I know it’s a fairly complex template, but it works well in the editor, so… ?

Post the entire template sensor. Where do you calculate hours_delay, how and where do you use the variable eventually? Because this indeed does not produce a result on its own. It might be the variable is defined in a different scope then where you need the result.

[solved] As you suggested, I again put every variable “under the microscope” and examined carefully how each one is defined - and indeed it was my mistake. This is the correct template:

 {% set index = two_days.index(two_days | select('<=', price_limit) | first) if two_days | select('<=', price_limit) | first is defined else -1 %}

I had mistakenly used current instead of price_limit as my target object.
That’s what can happen after hours of debugging: one goes completely blind.
Thank you so much - just by asking the right question you put me on the right track :+1:

1 Like