Dynamically set device_class on template

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' }}

This is invalid… How can I do it?

You cant. The device_class option does not accept templates.

If an option accepts a template it will explicitly say so in the docs

brave_screenshot_www.home-assistant.io

If the option does not state this then you can’t use a template.

:roll_eyes:

If you can’t recognise when an LLM is bullshitting you then don’t use it.

1 Like

Thanks a lot!!!
When I have a blank page and no idea what to write… also a dumb idea could kick start writing… :nerd_face:

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).

Everything that it is saying is completely wrong. It’s using the wrong lingo, and it’s making up a reason why it isn’t working.