Option to template the keys in data_template in addition to only values

I would like to be able to template keys instead of only values. For example, in this script where I use a choose, most options only differ in the keys.

That means that I could rewrite this:

- conditions: # input_boolean.desk_mode changed
    condition: template
    value_template: "{{ trigger_entity_id == 'input_boolean.{}_{}'.format(name, attribute) }}"
  sequence:
    service: kef_custom.set_mode
    data_template:
      entity_id: "{{ 'media_player.{}'.format(name) }}"
      desk_mode: "{{ trigger_to_state }}"
- conditions: # input_boolean.wall_mode changed
    condition: template
    value_template: "{{ trigger_entity_id == 'input_boolean.{}_{}'.format(name, attribute) }}"
  sequence:
    service: kef_custom.set_mode
    data_template:
      entity_id: "{{ 'media_player.{}'.format(name) }}"
      wall_mode: "{{ trigger_to_state }}"
- conditions: # input_boolean.phase_correction changed
    condition: template
    value_template: "{{ trigger_entity_id == 'input_boolean.{}_{}'.format(name, attribute) }}"
  sequence:
    service: kef_custom.set_mode
    data_template:
      entity_id: "{{ 'media_player.{}'.format(name) }}"
      phase_correction: "{{ trigger_to_state }}"
- conditions: # ienput_boolean.high_pass changd
    condition: template
    value_template: "{{ trigger_entity_id == 'input_boolean.{}_{}'.format(name, attribute) }}"
  sequence:
    service: kef_custom.set_mode
    data_template:
      entity_id: "{{ 'media_player.{}'.format(name) }}"
      high_pass: "{{ trigger_to_state }}"

into this

- conditions:
    condition: template
    value_template: "{{ trigger_entity_id == 'input_boolean.{}_{}'.format(name, attribute) }}"
  sequence:
    service: kef_custom.set_mode
    data_template:
      entity_id: "{{ 'media_player.{}'.format(name) }}"
      "{{ attribute }}": "{{ trigger_to_state }}"

Isn’t this a limitation of Jinja?

No, AFAIU, the keys would just have to be parsed by Jinja2, whereas now only the values are parsed.

Looking at the source code here, it seems the change might be from

return {key: render_complex(item, variables) for key, item in value.items()}

to

return {render_complex(key, variables): render_complex(item, variables) for key, item in value.items()}

Would love to see this one. I know I’ve personally answered a number of posts around the forum where I had to explain that only strings are templatable not objects and their keys and I’m hardly the most prolific poster around here. So I think a good chunk of users have hit this WTH moment.

I’ve started to implement his myself in https://github.com/home-assistant/core/pull/39008 :tada:

3 Likes

And it’s merged! Is this the firs t"What the Heck?!" that’s solved? :fire:

2 Likes

Nope :slight_smile: