In 2022.5 a “this” variable was introduced:
Template entities now have a
this
variable available, which is a reference to the state of the template entity itself.
Please have a look at this example:
sensor:
- platform: template
sensors:
test_this_template:
value_template: >-
{% if is_state("input_boolean.test_boolean","on") -%}
{{ "red" }}
{%- else -%}
{{ "brown" }}
{%- endif %}
attribute_templates:
color: >-
{{ states(this.entity_id) }}
availability_template: >-
{{ true }}
This seems to work.
But let’s compare with a bit different implementation:
attribute_templates:
color: >-
{{ states("sensor.test_this_template") }}
Here the attribute’s value is defined based on the sensor’s state.
I guess that the difference is that:
- Using “
this
” - using the current sensor’s state. - Using “
sensor.test_this_template
” - using the previous sensor’s state.
Although in this particular test case the results are same, I wonder is it correct to use the “this
” variable.
State & attributes may change asynchronously, this may cause some problems… Probably using external sensors to define attributes or state could be more reliable in some cases.
Please correct me if I am wrong.
Test card:
type: entities
entities:
- entity: input_boolean.test_boolean
name: red color
- type: section
label: sensor with "this"
- entity: sensor.test_this_template
name: state
- type: attribute
entity: sensor.test_this_template
attribute: color
name: '"color" attribute'
- type: section
label: sensor with entity_id
- entity: sensor.test_this_template_2
name: state
- type: attribute
entity: sensor.test_this_template_2
attribute: color
name: '"color" attribute'
1 post - 1 participant