Support Variables in Template Sensors

Tags: #<Tag:0x00007f326b48b530>

Release 0.115 introduced Variables for automations and scripts. Variables would also be useful for creating Template Sensors, Template Binary Sensors, Template Switches, etc.

For example, here’s a Template Sensor I use to report the quantity of open doors. It also has an attribute reporting the names of all open doors. The two templates it uses are nearly identical.

    open_doors:
      friendly_name: 'Open Doors'
      value_template: >
        {{ expand('group.doors_all')
          | selectattr('state', 'eq', 'on')
          | list | count }}
      attribute_templates:
        names: >-
          {{ expand('group.doors_all')
            | selectattr('state', 'eq', 'on')
            | map(attribute='name') | list | join(', ') }}

If variables were available, the resulting Template Sensor would have less duplication:

    open_doors:
      friendly_name: 'Open Doors'
      variables:
        doors: >
          {{ expand('group.doors_all')
             | selectattr('state', 'eq', 'on')
             | map(attribute='name') | list }}
      value_template: "{{ doors | count }}"
      attribute_templates:
        names: "{{ doors | join(', ') }}"