diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index 2dcdce9e019..ca399161b25 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -125,8 +125,11 @@ class MqttSensor(MqttEntity, SensorEntity): template = self._config.get(CONF_VALUE_TEMPLATE) if template is not None: + variables = {"entity_id": self.entity_id} payload = template.async_render_with_possible_json_value( - payload, self._state + payload, + self._state, + variables=variables, ) self._state = payload self.async_write_ha_state() diff --git a/tests/components/mqtt/test_sensor.py b/tests/components/mqtt/test_sensor.py index 373048f6f1a..c6ebbe98dc4 100644 --- a/tests/components/mqtt/test_sensor.py +++ b/tests/components/mqtt/test_sensor.py @@ -640,3 +640,31 @@ async def test_entity_disabled_by_default(hass, mqtt_mock): await help_test_entity_disabled_by_default( hass, mqtt_mock, sensor.DOMAIN, DEFAULT_CONFIG ) + + +async def test_value_template_with_entity_id(hass, mqtt_mock): + """Test the access to attributes in value_template via the entity_id.""" + assert await async_setup_component( + hass, + sensor.DOMAIN, + { + sensor.DOMAIN: { + "platform": "mqtt", + "name": "test", + "state_topic": "test-topic", + "unit_of_measurement": "fav unit", + "value_template": '\ + {% if state_attr(entity_id, "friendly_name") == "test" %} \ + {{ value | int + 1 }} \ + {% else %} \ + {{ value }} \ + {% endif %}', + } + }, + ) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "test-topic", "100") + state = hass.states.get("sensor.test") + + assert state.state == "101"