Hi,
I want to create a binary sensor whose status is formed from the difference of 2 temperatures. In addition, I would like to have the current temperature difference as an attribute.
In the template editor this is as expected:
None of the suggestions you have received so far is correct for the simple reason that a Jinja2 variable defined in an option is not defined outside of the option. Its “scope” is limited to the option where it’s defined.
The Jinja2 variable td is defined in the states option and cannot be referenced in another option, like you tried to do in tempdiff.
You will have to compute the value again in tempdiff.
You should supply the float filter with a default value. If you don’t and it receives a value it can’t convert (like unavailable) it will fail with an error message. In the example I posted, I have specified 0 as the default value.
You may also wish to consider using the availability option to confirm sensor.home_temperature and sensor.terraza_temperature have numeric values.
You may also wish to vote for this Feature Request:
That scope definition is really annoying.
I checked that there were no loop scopes, because I knew that could cause issues, but I did not know this scope issue.
i am glad I do most of my stuff in NodeRed
FWIW, like most programming tools, Node Red’s nodes and JavaScript variables also have a scope.
What’s missing in Template Sensors, but exists in scripts and automations, is the concept of a “script variable” (whose scope is global for the script/automation where it’s defined).
I thought of the scoped variable (simply because I read about it last week, because I don’t know a lot about templating), but since it worked on Dev Tools Template, I assumed it wasn’t the case. My apologies for any misinformation!
The Template Editor is a Jinja2 processor for testing Jinja2 templates. It doesn’t process or validate YAML.
The Template Editor is unaware that state: and tempdiff: are separate YAML keys. It simply sees them as text and focuses exclusively on what it detects to be Jinja2 statements.
Thanks for the explanation of the variable scope and the Template Editor. So I have to make the clalculation twice, one for the state and the other for the attribute, which is rather non-elegant.
Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions.
For more information about the Solution tag, refer to guideline 21 in the FAQ.