How can I template both keys and values?

Is there a way to template both keys and values?

I’ve tried:

  actions: |-
      {%- for entity in room_entities -%}
      - action: 'autoroom_{{ entity }}'
        title: '{{ state_attr(entity, 'friendly_name') }}'
      {%- endfor %}

but it becomes

    actions: |-
      - action: 'autoroom_light.wohnzimmer_dimmer'
        title: 'Wohnzimmer Dimme

and it should become

    actions:
      - action: 'autoroom_light.wohnzimmer_dimmer'
        title: 'Wohnzimmer Dimme

Thanks!

You will need to work with JSON objects.

actions: >-
  {% set room_entities=[ "Wohnzimmer","Kueche","Bad","Schlafzimmer" ] %}
  {% set data = namespace(actions=[]) %}
  {%- for entity in room_entities -%}
    {% set action_json = {"action": 'autoroom_'+ entity|string,
      "title": state_attr(entity, 'friendly_name')|string } %}
    {% set data.actions = data.actions + [ action_json ] %}
  {%- endfor %}
  {{ data.actions }}
  {# data.actions[1] #}
1 Like

by supplying actions with a list of dictionaries assuming it can be templated

actions: >
  {% set ns = namespace(actions=[]) %}
  {% for entity in room_entities %}
    {% set ns.actions = ns.actions + [ {"action": "autoroom_" ~ entity, "title": state_attr(entity, "friendly_name") } ] %}
  {% enfor %}
  {{ ns.actions }}

However, i should say that this seems odd. What actions are you referring to? Typically actions are a service and a data section. Those cannot be templated like this, however the entire data section can.

2 Likes

I use the action section with the notify.mobile_app_xyz service:

      - service: |-
          {% set y = expand(presence_notification_entities_str.keys()) | selectattr('state', 'in', presence_states) | map(attribute='entity_id') | first %}
          {{ presence_notification_entities_str.get(y) if y | length > 0 else 'none' }}
        data_template:
          message: "Click on a device to toggle its state"
          title: "{{expand(presence_notification_entities_str.keys()) | selectattr('state', 'in', presence_states) | map(attribute='state') | first }} - ble"
          data:
            color: '#154c79'
            sticky: 'true'
            channel: 'Ble Notify'
            importance: high
            persistent: true
            tag: ble_persistent
            notification_icon: 'mdi:pin'
            image: "https://ha/local/{{expand(presence_notification_entities_str.keys()) | selectattr('state', 'in', presence_states) | map(attribute='state') | first }}.png"
            actions: >
              {% set ns = namespace(actions=[]) %}
              {% for entity in room_entities %}
                {% set ns.actions = ns.actions + [ {"action": "autoroom_" ~ entity, "title": state_attr(entity, "friendly_name") } ] %}
              {% endfor %}
              {{ ns.actions }}