Create nested attributes in Template Sensor

Hello everyone,

I’m having trouble creating nested attributes.

With this code, I can at least get values ​​into the attributes.

template:
  - trigger:
      - trigger: time
        at: "23:59:00"
    sensor:
      - name: Garmin_Statistiken
        state:  |
          {% if now().day == 31 and now().month == 12 %}
          {% set zustand = int(states('sensor.garmin_statistiken')) +1 %}{{zustand | string }}
          {% endif %}
        attributes: 
          year: >
            {% set lastyear = int(now().timestamp() | timestamp_custom('%Y'))-1 %}
            {{ lastyear }}
          wandern_sessions: >
            {{ states('counter.garmin_wandern_sessions') }}
          wandern_hrs: >
            {{ states('input_number.garmin_wandern_year_hrs') }}
          wandern_kcal: >
            {{ states('input_number.garmin_wandern_kcal_year') }}
          wandern_km: >
            {{ states('input_number.garmin_wandern_year_km') }}
        state_class: total
        unique_id: "Garmin_Statistiken"

the result is then as follows:

state_class: total
friendly_name: Garmin_Statistiken
year: 2024
wandern_sessions: 2
wandern_hrs: 4.92
wandern_kcal: 2303
wandern_km: 14.57

almost right, First Problem, I would like to have this as nested attributes in the format:

state_class: total
friendly_name: Garmin_Statistiken
yearly_stats:
- year: 2024
  wandern_sessions: 2
  wandern_hrs: 4.92
  wandern_kcal: 2303
  wandern_km: 14.57

Second, further execution of the script doesn’t add to it, but rather overwrites it.

Perhaps someone has a clever idea how I can implement this?

Many thanks & regards

1 Like