UI Template Editor - Variables

I tried to build a battery level checking scipt in the UI Editor.

Sequence:

a) condition - template:

{# Prozent fuer low_batt #}
{% set battery_alert = 30|int %}

{# Zwave Sensors #}
{% set low_batt_zwave = states.zwave | selectattr('attributes.battery_level', 'defined') | selectattr('attributes.battery_level','<', battery_alert ) | map(attribute='name') | list | join(', ') %}

{# Zigbee Sensors #}
{% set low_batt_sensor = states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('attributes.battery', 'defined') | selectattr('attributes.battery','<', battery_alert ) | map(attribute='name') | list | join(', ') %}

{# NUKI Lock #}
{% set low_batt_lock = states.lock | selectattr('attributes.battery_critical', 'true') | map(attribute='name') | list | join(', ') %}

{# Return TRUE if low_batt found #}
{{ (low_batt_zwave|length > 1) or (low_batt_sensor|length >1) or (lock_batt_lock|length >1) }}

b) call service: notify.notify

message: >
  Batteries below {{ battery_alert }} on the following devices: {{ low_batt_zwave }} {{low_batt_sensor}}
title: Low Battery Warning

The problem is, that the variable defined in the condition (eg “battery_alert”, “low_batt_zwave”) are empty. I don’t really understand that, because that is the same script…

Any advice?

Thx!

Assigned variables are local to the template, not global. For a global variable you can use input texts, input numbers, the variable custom component or store them in mqtt topics.

Just to clarify what @tom_l is saying, it’s local to the yaml field only. Not the entire file. Your whole script has to exist inside the message: field.

Another point : why are you converting 30 (an integer) to an integer ?
It would be different if you were looking at a stored ‘state’ value or if you were looking at ‘30’

thanks - but this is the SAME script… first block is a condition, second block is call service… why are the variables not available in the “call service” block?

… when I am using the UI editor, I can only choose between condition OR call service.

My idea was to make a condition which returns true/false and store the message text in a variable. Then I want a notifiy call which the value of the variable (to avoid calling the whole selectattr again).

the problem is that the variables are only available in the condition block but NOT in the call service block :frowning:

The variables are local to each template, not the whole script.

It’s not the same script. What you’re referring to is the file (or automation).

The script is only contained in a single yaml field as I said above. So in your line of thought based on what you’ve said, your entire script should be contained in the service block’s message field.

{% JINJA HERE IS OUTSIDE THE SCOPE OF MESSAGE AND NOTHING WILL GET TO MESSAGE %}

message: >
  {% EVERYTHING DECLARED AND CONTAINED HERE %}

thanks for the clarification