I’m trying to write a template in a macro to reuse same code on different devices.
I described the use in tuya temperature/humidity.
When I try to set device_class dynamically (gpt suggested)
device_class: >
{% set requested_class = device_class | default('temperature') %}
{% set valid_classes = [
'temperature', 'humidity', 'power', 'voltage',
'current', 'energy', 'battery'
] %}
{{ requested_class if requested_class in valid_classes else 'temperature' }}
with gpt 4.1 got this answer that confirms that it is getting better:
Your configuration snippet shows an attempt to create a reusable template “macro” for sensors within the packages: integration in Home Assistant, using Jinja-like variable placeholders. Here’s an analysis and explanation:
…
Reality: Is This Approach Supported?
Home Assistant & Variables in YAML Sensor Definitions
Jinja in YAML keys or structure is not supported: Home Assistant only processes Jinja within specific fields (e.g., the state: or value_template: of a sensor), NOT throughout the YAML or as a macro system.
You cannot define a “macro sensor” like this and “include” or “instantiate” it multiple times with different variables at the YAML level.
Your example would not work as a true macro/template in current or past Home Assistant, up to version 2025.04 (and likely beyond unless a major feature is introduced).