Template sensor: using "this" variable

My understanding is you should get the same result whether you do this.state or states('<entity ID>') in an attribute or icon template. Although just an FYI I’m not sure your test is really valid. You seem to be doing states(this.entity_id) instead of just this.state. states(this.entity_id) will always give the same result as states('<entity id>') since the entity ID doesn’t change, that’s basically testing the same thing twice.

Assuming this.state and states('<entity ID>') are equivalent, the advantages of using this.state IMO are:

  1. It’s shorter. Always a plus
  2. YAML anchors. If you have a few different sensors that are basically the same template but vary only in the ID of the entity (ex. one per room that does area_entities('<entity ID>') | <do stuff with those entities>) then you basically had to copy and paste that template before or employ some seriously hacky tricks with trigger IDs. Now you can just replace the hard-coded entity ID with this.entity_ID and actually use the same template repeatedly via YAML anchors.

There’s probably others but #2 was what made me excited about it personally. Although currently this isn’t available in trigger template entities so I’m still waiting for that.

1 Like