How to use 'local' variables in sensor-templates?! [defined @ templates:variables level]

Hi,

I hope here is somebody with ‘extended’ knowledge who is willing to support a grumpy old guy. I have a developer background and working with ha since more then two years - I am also providing multiple custom integrations - so I would consider myself not as a rookie.

But since a couple of days I am struggling (for me personal use) with configuration of (multiple) template sensors via yaml. My challenge is, that my sensors will use some base information that must be calculated from different other sensor data. So instead of providing the (complex) code with every single template-sensor I want to make use of ‘variables’ declared in my sensor template yaml file (mainly for clean code reasons - to avoid code duplication)…

The documentation indicates, that HA is supporting variables (in the templates integration) - Template - Home Assistant

But I am struggling (hard) to access/use a value of such a defined variable in a simple template sensor:

Here is my (very simple) example:

In my ha configuration.yaml:

homeassistant:
  packages:
    my_var_test: !include sensor-tests.yaml

and the sensor-tests.yaml:

# https://www.home-assistant.io/integrations/template
# https://www.home-assistant.io/docs/configuration/templating/
# https://community.home-assistant.io/t/global-template-variables/367611/4

template:
  - variables:
      var001: "{{now()}}"
      var002: "MyValue"

  - sensor:
      - name: "VariablesTestTemplate"
        unique_id: var_test_template_sensor
        state: >
          {{var001}} {{var002}}

but when in the log’s I can see:

  • 2024-11-16 10:25:00.354 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: ‘var001’ is undefined when rendering ‘{{var001}} {{var002}}’
  • 2024-11-16 10:25:00.354 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: ‘var002’ is undefined when rendering ‘{{var001}} {{var002}}’

So ok looks like, that in the scope of the sensor my declared variables does not exist… I could not find a way to access the values of my (external) declared variables, tried multiple things like '{{this.var001}} or {{variables.var001}} or {{this.parent.var001}}… but all of that failed as well…

So I initially thought, that only in blueprints the variables will be populated & send via the **kwargs - BUT when I make use of an additional external test.jinja file (placed in ‘custom_templates’ like this one:

{% macro test_macro2() -%}
{{now()}}
{%- endmacro %}

{% set test_variable2 = test_macro2() %}

then I am able to access these external variables (& macros) from my sensor:

template:
  - sensor:
      - name: "VariablesTestTemplate"
        unique_id: var_test_template_sensor
        state: >
          {% import 'test.jinja' as t %}
          {{ t.test_macro2() }} {{ t.test_variable2 }}

So before I now refactor all my stuff (and move my variables (that I want to declare in my ‘sensor-tests.yaml’ file) to a separate custom_templates/*.jinja file) I wanted to ask, if somebody of you might have a hint, how I can access a declared variable value (no matter if static value or another template) from such a templates platform sensor definiation?!

Right now your variables are separated from your sensor because you have a dash in front of sensor, which makes it a separate template item. Replace the dash with a space and the variables will be attached to the sensor.

1 Like

Thanks for your fast reply - so when I understood you correctly, then I must use it in ‘this’ way:

template:
  - variables:
      var001: "{{now()}}"
      var002: "MyValue"
    
    sensor:
      - name: "VariablesTestTemplate A"
        unique_id: var_test_template_a_sensor
        state: "AA {{var001}}"

      - name: "VariablesTestTemplate B"
        unique_id: var_test_template_b_sensor
        state: "BB {{var002}}"

but the result is still the same - log output is still the same Template variable warning: 'var001' is undefined when rendering 'AA {{var001}}'

I’ll guess I have to go the route via the ‘include’ of a separate custom_templates/*.jinja file (that contains the logic for all the sensors)…

[quote=“marq24, post:3, topic:795548”]
then this would mean, that I must duplicated my “variables” section into each sensor…
[/quote]

No, just don’t start a new list item. You can have multiple sensors (as well as other template entities types) under the same list item:

```yaml
template:
- variables:
var001: “{{now()}}”
var002: “MyValue”

sensor:
- name: “VariablesTestTemplate A”
unique_id: var_test_template_a_sensor
state: “{{var001}} {{var002}}”

- name: “VariablesTestTemplate B”
unique_id: var_test_template_b_sensor
state: “{{var002}} {{var001}}”

binary_sensor:
- name: Is it the future?
state: “{{ var001 > (var001 + timedelta(days=1)) }}”

```

EDIT: This doesn’t work

should I be able to do this:

template:

  - variables:
      vj_marijn: '1999-06-27'|as_datetime|as_local

and next use vj_marijn in trigger based templates below that?

    sensor:

      - unique_id: marijn_verjaardag
        state: >

          {% set event = vj_marijn %}
          {% set year = 1 if event.month < now().month or
                            (event.month == now().month and event.day < now().day)
                         else 0 %}
          {% from 'easy_time.jinja' import count_the_days %}
          {{count_the_days(event.replace(year=now().year + year))}}

I get an error now, as OP mentions: is undefined
I had those date strings in custom_templates before

{% set vj_marijn = '1999-06-27'|as_datetime|as_local %}

and imported them, which works fine,

Love to give the variables a try though

@Didgeridrew Thanks for your clarification (looks like that I made a stupid mistake when I tried this for the first time)…

Anyhow still with the given example (without the binary_sensor which cause an exception/stacktrace) I still have the issue, that the helpers/template.py cause the warning, that the var001 & var002 are not populated (Template variable warning: 'var001' is undefined when rendering...) and the sensor state is empty - I am using ha 2024.11.2 in a docker container for testing

simplest example:

template:

  - variables:
      naam: Marius #should be available for the template sensors below this, according to the documentation
 
 - trigger:
      - trigger: state
        entity_id: sensor.date
  - sensor:
      - unique_id:
        state:
        etcetc

and a sensor below that using the variable:

        attributes:
          test_variable: >
            {{naam}}

remains empty

same when used as a straight forward template sensor:

  - sensor:
      - unique_id: testing_template_variables
        state: >
          {{naam}}
        name: >
          {{naam}}

no name, no state:

Mea Culpa… :man_facepalming:

You are correct, upon testing the variables do not seem to be populated at all. Looking back at my other sensors it looks like I have only ever set values to variables in the action block of trigger-based template entities.

The variables key does seem to work in the new template blueprints… but that’s not useful for what you are trying to do.

Your example has the same issue that Petro pointed out from OP’s first post… local scope is broken by everything being separate items in the list.

So would that amount to an issue….?

Since the variables block was just added with the template blueprints and those blueprints are still a work in progress… it’s likely they just haven’t gotten around to it yet.

@marq24
Looking at the new entry for variables in the template docs it does specify that the value must be a string, not even limited templates appear to be supported at this point.

once again - thanks for your feedback! [I have edited my second post to include both cases - “str” and “template”] - as we know now, both cases seams to be (currently) not supported… and I also realized this afternoon, that this variables are brand new (and probably nobody had the idea to use it in the way I just tried)…

So we will see, if this will be tackled in one of the future releases… In the meantime I will share my current (work around) solution via including a import 'pow_vars.jinja' as i shortly…