How to assign attributes to a template sensor

I am trying the following code:

      - name: "active_sleepers"
        state: >-
            {% set ns = namespace(active_sleeper_rooms = []) %}  {# create a namespace object to store variables #}
            {%- for boolean in states.input_boolean -%} 
              {% if boolean.state == "on" and "input_boolean.sleeper_" in boolean.entity_id %} 
                {% set sensor = boolean.entity_id | replace('input_boolean.sleeper_in_','') %}
                  {% set ns.active_sleeper_rooms = ns.active_sleeper_rooms + [sensor] %}
              {%- endif %}
            {% endfor %}
            {{ ns.active_sleeper_rooms | wordcount }}
        attributes: >-  
            {% set ns = namespace(index=0, tuples=[]) %}
            {%- for boolean in states.input_boolean -%}
              {% if boolean.state == "on" and "input_boolean.sleeper_" in boolean.entity_id %}
                {% set sensor = boolean.entity_id | replace('input_boolean.sleeper_in_', '') %}
                {% set ns.index = ns.index + 1 %}
                {% set t = (ns.index, sensor) %}
                {% set ns.tuples = ns.tuples + [t] %}
              {%- endif %}
            {% endfor %}
            {% set data = dict.from_keys(ns.tuples) %}
            {{ data }}

But keep getting a dictionnary error for the attribute.

Does anyone has an idea?

You can’t template the attributes field, only fields within the attributes field.

That is a bummer; If I may, this is what I am trying to achieve:

Using this template sensor (And another dozen, but that is out of scope ) trying to determine where I am sleeping.

To do so, I need this following sensor to be an array. The problem is that when using {{ sensor | first }}
I get the first character, instead of the first object.

Is there a way to achieve this since templates don’t seem to be able to old arrays?


      - name: "active_sleeper_rooms"
        state: >-
            {% set ns = namespace(active_sleeper_rooms = []) %}  {# create a namespace object to store variables #}
            {%- for boolean in states.input_boolean -%} 
              {% if boolean.state == "on" and "input_boolean.sleeper_" in boolean.entity_id %} 
                {% set sensor = boolean.entity_id | replace('input_boolean.sleeper_in_','') %}
                  {% set ns.active_sleeper_rooms = ns.active_sleeper_rooms + [sensor] %}
              {%- endif %}
            {% endfor %}
            {{ ns.active_sleeper_rooms }}

as a sidebar, you can simplify your templates.

      - name: "active_sleepers"
        state: >-
          {{ states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") | list | count }}
        attributes:
          items: >
            {% set ns = namespace(items=[]) %}
            {% for inp in states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") %}
              {% set ns.items = ns.items + [ (loop.index, inp.entity_id | replace('input_boolean.sleeper_', '') ] %}
            {% endfor %}
            {{ dict.from_keys(ns.items) }}

well, in your template sensor is a string, so the first item in a string will always be a character.

If you were to assume that the last input boolean you used was where you slept, then your template could simply be:

{{ states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") | sort(attribute='last_updated', reverse=True) | map(attribute="name") | first | default }}

This was actually very usefull,

I’ve now came up with a few sensors that are all merged together to try and determine my current activity:

          
      - name: "Maxi Location"
        unique_id: "maxi_location" 
        state: >-            
            {% set braceletroom = states('sensor.b7bracelet1') %}
            {% set phoneroom = states('sensor.phone_fold4') %}
            {% set gpslocation = states('device_tracker.phone_galaxy_fold_4') %}

              {% if braceletroom != "not_home" %}      
                {% set location = braceletroom %}
              {% elif phoneroom != "not_home" %}
                {% set location = phoneroom %}
              {% elif gpslocation != "not_home"%}
                {% set location = "At " + gpslocation %}
              {% else %}
                {% set location = unkown %}
              {% endif %}
              {{ location }}

      - name: "Maxis Current Game"
        unique_id: "currentgamemaxi" 
        state: >-
            {% if state_attr('sensor.maxi1134_8202', 'game') %}
            {{ state_attr('sensor.maxi1134_8202', 'game') }}
            {% elif  state_attr('sensor.steam_maxi', 'game') %}
            {{state_attr('sensor.steam_maxi', 'game')}}
            {% else %} idle
            {% endif %}
      - name: "Maxis Current Discord Game"
        state: >-
            {% if state_attr('sensor.maxi1134_8202', 'game') %}
            {{ state_attr('sensor.maxi1134_8202', 'game') }}
            {% else %}idle
            {% endif %}
      - name: "Maxis Current Steam Game"
        state: >-
            {% if  state_attr('sensor.steam_maxi', 'game') %}
            {{state_attr('sensor.steam_maxi', 'game')}}
            {% else %}idle
            {% endif %} 

      - name: "amount partners home"
        state: >-
            {# set the ammount of partners home #}
            {% if states('person.maximiliano') == "home" %}   {# If I am home, the amount should be zone.home -1 #}
              {% set partnershome = states('zone.home')  | int - 1  %}
            {% else %}{# If I am not home, the amount should be zone.home #}
              {% set partnershome = states('zone.home')  | int  %}
            {% endif %}
            {{partnershome | int }}

      - name: "amount friends home"
        state: >-
             {# Set friendshome to the amount of friends #}
             {% set friendshome = states('sensor.guest_wifi_count') | int - states('sensor.amount_partners_home') | int  %}
             {{friendshome}}


      - name: "amount people home"
        state: >-
             {# Set peoplehome to the amount of people #}
             {% set peoplehome = states('sensor.amount_friends_home') | int + states('sensor.amount_partners_home') | int  %} 
             {{peoplehome}}

      

      - name: "last active room"
        state: >-
            {% set rooms = ["office","bedroom","kitchen","hotbox","closet","livingroom","server"] %}
            {# Check for motionsensors in the rooms and then store them in a list #}
            {% set ns = namespace( active_motion_sensors = [] )%}
            {% for allowed_rooms in rooms %}
              {% for state in states.binary_sensor -%} 
                {% if allowed_rooms in state.entity_id and "binary_sensor.sensor_" in state.entity_id and "occupancy" in state.entity_id %} 
                  {% set sensor = {'entity_id': state.entity_id, 'last_changed': state.last_changed} %}
                    {% set ns.active_motion_sensors = ns.active_motion_sensors + [sensor] %}
                {%- endif %}
              {% endfor %}
            {% endfor %}



            {# sorts the motion sensor list to output the active room where there was last motion#}
            {% set sorted_sensors = ns.active_motion_sensors | sort(attribute='last_changed') %}
            {% set last_sensor = sorted_sensors | last %}

            {# set the lasttvactiveroom variant #}
            {% set room_before_split =last_sensor.entity_id | replace('binary_sensor.sensor_','')| replace('_motion_occupancy','')%}                            
            {% set lasttvactiveroom = room_before_split.split('_') | first %}     
            {{lasttvactiveroom}}

      - name: "active_sleeper_rooms"
        state: >-
            {% set ns = namespace(active_sleeper_rooms = []) %}  {# create a namespace object to store variables #}
            {%- for boolean in states.input_boolean -%} 
              {% if boolean.state == "on" and "input_boolean.sleeper_" in boolean.entity_id %} 
                {% set sensor = boolean.entity_id | replace('input_boolean.sleeper_in_','') %}
                  {% set ns.active_sleeper_rooms = ns.active_sleeper_rooms + [sensor] %}
              {%- endif %}
            {% endfor %}
            {{ ns.active_sleeper_rooms }}

      - name: "active_sleepers"
        state: >-
          {{ states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") | list | count }}
        attributes:
          rooms: >
            {% set ns = namespace(items=[]) %}
            {% for inp in states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") %}
              {% set ns.items = ns.items  + [ (loop.index, inp.entity_id  | replace('input_boolean.sleeper_in_','') ) ] %}
            {% endfor %}
            {{ dict.from_keys(ns.items) }}

      - name: "active_sleeper_amount"
        state: >-
            {{ states('sensor.active_sleeper_rooms') | wordcount }}

            
      - name: "active_chromecast_rooms"
        state: >-
            {% set ns = namespace(mediaactiverooms = []) %}  {# create a namespace object to store variables #}
            {% for media_player in states.media_player -%} 
              {%- if  "plex" not in media_player.entity_id and "chromecast" in media_player.entity_id and "owntone" not in media_player.entity_id and "roku" not in media_player.entity_id and "speaker" not in media_player.entity_id and "display" not in media_player.entity_id -%}  
                {%- if media_player.state == 'playing' -%}
                {% set currentroomname = media_player.entity_id | replace('media_player.','') | replace('chromecast.','') %}
                  {%- set ns.mediaactiverooms = ns.mediaactiverooms + [currentroomname.split('_') | first] -%}   
                {%- endif -%}
              {%- endif -%}
            {% endfor %} 
            {{ ns.mediaactiverooms | unique | list}}
      - name: "active_speakers_rooms"
        state: >-
            {% set ns = namespace(mediaactiverooms = []) %}  {# create a namespace object to store variables #}
            {% for media_player in states.media_player -%} 
              {%- if  "plex" not in media_player.entity_id and "speaker" in media_player.entity_id and "owntone" not in media_player.entity_id and "roku" not in media_player.entity_id and "chromecast" not in media_player.entity_id and "group" not in media_player.entity_id and "display" not in media_player.entity_id -%}  
                {%- if media_player.state == 'playing' -%}
                {% set currentroomname = media_player.entity_id | replace('media_player.','') | replace('speaker.','') %}
                  {%- set ns.mediaactiverooms = ns.mediaactiverooms + [currentroomname.split('_') | first] -%}   
                {%- endif -%}
              {%- endif -%}
            {% endfor %} 
            {{ ns.mediaactiverooms | unique | list}}

      - name: Is maxi asleep?
        state: >
            {% set room = states.sensor.maxi_location.state %}  {# get the current maxi location sensor state #}
            {% set sleeperamount = states('sensor.active_sleeper_amount') | int %}
            {% set activesleeperrooms = states('sensor.active_sleeper_rooms') %}
            {% set lasttvactiveroom = states('sensor.last_active_room') %}
            {% set phone_sleep_confidence = states('sensor.phone_fold4_sleep_confidence') | int %}
            {% set sleepingstate = "awake" %}
            {% if sleeperamount > 0 %}
                {% if states.binary_sensor.maxi_alone.state == "on" %}
                    {# if the maxi_alone sensor is on, indicating there is only maxi present #}
                    {% if sleeperamount > 1 %}
                        {# if there is more than one "sleeper" input_boolean that is "on" #}
                        {% if room in activesleeperrooms %}
                            {% set sleepingstate = "asleep" %}
                        {% elif lasttvactiveroom in activesleeperrooms  %}
                           {% set sleepingstate = "asleep" %}
                        {% endif %}
                    {% elif sleeperamount == 1 %}
                        {# if there is only one "sleeper" input_boolean that is "on" #}
                        {% set sleepingstate = "asleep" %}   {# set the roomname to the only "sleeper" input_boolean that is "on" #}
                    {% endif %}
                {% elif states.binary_sensor.maxi_alone.state == "off" and room in activesleeperrooms %}
                    {# if the maxi_alone sensor is off, it indicates that there is more than maxi present #}
                    {% set sleepingstate = "asleep" %}
                {% elif states.binary_sensor.maxi_alone.state == "not_home" %}
                    {# if maxi is not home #}
                    {# check phone sleep confidence to determine if I am sleeping #}
                    {% if phone_sleep_confidence > 94 and room != "not_home"  %}
                        {# Assume I am sleeping if confidence is over 94% #}
                        {% set sleepingstate = "asleep" %} {# set sleeping spot at current outside of home location #}
                    {% endif %}
                {% endif %}
            {% else %}
                {% if phone_sleep_confidence > 94 %}
                    {% set sleepingstate = "asleep" %} {# set sleeping spot at current outside of home location #}
                {% endif %}
            {% endif %}
            {{ sleepingstate }}
        attributes:
          location: >
            {% set room = states.sensor.maxi_location.state %}  {# get the current maxi location sensor state #}
            {% set sleeperamount = states('sensor.active_sleeper_amount') | int %}
            {% set activesleeperrooms = states('sensor.active_sleeper_rooms') %}
            {% set lasttvactiveroom = states('sensor.last_active_room') %}  
            {% set phone_sleep_confidence = states('sensor.phone_fold4_sleep_confidence') | int %}
            {% set sleepingspot = "" %}
            {% if sleeperamount > 0 %}
              {% if states.binary_sensor.maxi_alone.state == "on" %}  {# if the maxi_alone sensor is on, indicating there is only maxi present #}
                {% if sleeperamount > 1 %}  {# if there is more than one "sleeper" input_boolean that is "on" #}
                {% if room in activesleeperrooms %}
                    {% set sleepingspot = room %}
                  {% elif lasttvactiveroom in activesleeperrooms  %}
                    {% set sleepingspot = lasttvactiveroom %}
                  {% else %}
                  {# this below code set sleepingspots as the last sleeper that eas turned on#}
                  {% set sleepingspot =  states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") | sort(attribute='last_updated', reverse=True) | map(attribute="entity_id") | first | default | replace("input_boolean.sleeper_in_","") %}  
                  {% endif %}
              
                {% elif sleeperamount == 1 %}  {# if there is only one "sleeper" input_boolean that is "on" #}
                  {% set sleepingspot =  states.sensor.active_sleepers.attributes.rooms.1%}  {# set the roomname to the only "sleeper" input_boolean that is "on" #}
                {% endif %}  
              
              {% elif states.binary_sensor.maxi_alone.state == "off" %}  {# if the maxi_alone sensor is off, it indicates that there is more than maxi present #}
                  {# this below code set sleepingspots as the last sleeper that was turned on#}
                  {% set sleepingspot = states.input_boolean | selectattr('state','eq','on') | selectattr('entity_id','search',"input_boolean.sleeper_") | sort(attribute='last_updated', reverse=True) | map(attribute="entity_id") | first | default | replace("input_boolean.sleeper_in_","") %}  
              {% elif states.binary_sensor.maxi_alone.state == "not_home" %}  {# if maxi is not home #}
                  {# check phone sleep confidence to determine if I am sleeping #}
                  {% if phone_sleep_confidence > 94 and room != "not_home"  %} {# Assume I am sleeping if confidence is over 94% #}
                    {% set sleepingspot = room %} {# set sleeping spot at current outside of home location #}
                  {% endif %}
              {% endif %}
            {% else %}
              {% if phone_sleep_confidence > 94 %}
                      {% set sleepingspot = room %} {# set sleeping spot at current outside of home location #}
              {% endif %}
            {% endif %}
            {{ sleepingspot }}
            
      - name: "Where is maxi sleeping?"
        unique_id: maxi_sleeping_spot
        state: >-
          {{ state_attr('sensor.is_maxi_asleep', "location") }}

          
      - name: "Maxi current Activity"
        unique_id: maxi_current_activity
        state: >-
            {% set ns = namespace( activityname="unsure", mediaactiverooms=[],lasttvactiveroom = states('sensor.last_active_room'), active_sleepers_amount=0, allowed_ids=[],active_sleeper_rooms=[], motion_sensors=[], room = states.sensor.maxi_location.state, active_motion_sensors = [] ) %}  {# create a namespace object to store variables #}
            {% set room = states('sensor.maxi_location') %}
            {% set partnershome = states('sensor.amount_partners_home') | int  %}
            {% set friendshome = states('sensor.amount_friends_home') | int  %} {# Set friendshome to the amount of people #} 
            {% set peoplehome = states('sensor.amount_people_home')  %}{# Set peoplehome to the amount of people #}
            {% set ns.active_sleepers_amount = states('sensor.active_sleeper_amount') %}
            {% set ns.mediaactiverooms = states('sensor.active_chromecast_rooms') %}   


            {% if states.binary_sensor.maxi_alone.state == "on" %}  {# if the maxi_alone sensor is on, indicating there is only maxi present #}

                {# Set the activity as gaming if a game is launched #}
                {% if states('sensor.is_maxi_asleep') == "asleep" %}          
                      {% set ns.activityname = "Sleeping"  %}          
                {% elif states('sensor.currentgamemaxi') != "idle" %}          
                      {% set ns.activityname = "Playing a video game" %}          
                {% elif room == "office" and states('sensor.maxi1134_8202') != "idle" %}         
                      {% set ns.activityname = "Using the computer " %}          
                {% elif ns.activityname == "unsure" %}    
                  {% if ns.mediaactiverooms | length > 0 %}                    
                  {# Check if I am in a room with mediaplayback #}
                  {% for activeroom in ns.mediaactiverooms %}
                    {% if ns.room in activeroom %}                                                       
                  {% set ns.activityname = "Watching TV in the " + room %}
                    {% endif %}
                  {% endfor %}          
                    {% if ns.activityname == "unsure" %}                        
                      {% set ns.activityname = "Watching TV in the " + ns.lasttvactiveroom %}
                      {% endif %}
                  {% endif %}
                {% endif %} 



            {% elif states.binary_sensor.maxi_alone.state == "off" %}  {# if the maxi_alone sensor is off, it indicates that there is more than maxi present #}
              {% if friendshome == 0 and partnershome > 0  %} {# If mor than one user is home, and no guest are there.  #}
                      {# Need to greatly expand this to know what we are doing #}
                    {% if states('sensor.is_maxi_asleep') == "asleep"%}        {# if maxi is sleeping #}   
                        {% set ns.activityname = "whereg"  %}             
                    {% elif ns.active_sleepers_amount < partnershome and states('sensor.is_maxi_asleep') == "awake" %} {# Trigger if less people are asleep than are present and that is not maxi #}
                        {% if room in ns.mediaactiverooms %}
                            {% set ns.activityname = "Watching TV with girls in the " + room %}     
                        {% elif states('zone.home') == 2 and states('person.alexe') == home and room == "closet" and states('input_boolean.sleeper_in_closet') == "off" %}
                            {% set ns.activityname = "Playtime" %}                
                        {% elif states('zone.home') == 2 and states('person.myriam') == home and room == "closet" and states('input_boolean.sleeper_in_closet') == "off" %}
                            {% set ns.activityname = "Playtime" %}            {% else %}
                            {% set ns.activityname = "With girls in the " + room %}
                        {% endif %}
                    {% elif ns.active_sleepers_amount >=  partnershome  and states('sensor.is_maxi_asleep') == "awake" %} {# if more sleepers than users and maxi is awake#}
                        {% if states('sensor.currentgamemaxi') != "idle" %}          
                          {% set ns.activityname = "Playing " +  states('sensor.currentgamemaxi') %}         
                        {% elif room == "office" and states('sensor.maxi1134_8202') != "idle" %}    
                          {% set ns.activityname = "Using the computer " %}
                        {% elif room in ns.mediaactiverooms %}
                            {% set ns.activityname = "Watching TV in the " + room %}  
                        {% else %}
                            {% set ns.activityname = "todetermine" %}  
                        {% endif %}  
                    {% endif %}        
              {% elif friendshome > 0   %}     {# if we have more people over than users #}{# assume a chilling #}
                        {% set ns.activityname = "Chilling" %}



              {% else %}
              {% endif %}                      
            {% else %}
              EDGECASE
            {% endif %}
            {{ns.activityname }}

And


      maxi_sleeping:
        friendly_name: "Maxi is sleeping"
        delay_off:
          minutes: 0
        value_template: >-
          {{ not is_state('sensor.where_is_maxi_sleeping', '') }}```


Thanks a lot for the help!

On your original idea, you can almost do what you want if you make one attribute (field) and store the whole dictionary/JSON in it. You’ll need some extra parsing (possibly) depending on where you use the info.