Strange behavior of a sensor

Hello everyone,

I typed some code into the template editor:

          {%- set bat = namespace(data = []) %}
          {%- set batn = namespace(below = []) %}
          {% set bat.data = bat.data + states 
          |selectattr("attributes.device_class","defined")
          |selectattr("attributes.device_class", "search","battery")
          | map(attribute='entity_id')
          |list %}
           {%- for x in bat.data %}
           {%- if states(x) != "unavailable" %}         
          {%- if states(x)|int <= states("input_number.batteryniveau_alarm_3")|int %}   
          {%- set batn.below = batn.below + [ x ] %}
          {%- endif %}  
          {%- endif %}  
          {%- endfor %}
         {{ batn.below}}

and this results in the following result:

[‘sensor.motion_sensor_gemeen_gv_battery’, ‘sensor.hue_motion_verwarm_1ste_verd_battery’, ‘sensor.motion_sensor_2de_verdieping_battery’, ‘sensor.hue_motion_verwarm_2de_verd_battery’, ‘sensor.motion_sensor_1ste_verdieping_battery’, ‘sensor.hue_motion_dressing_battery’, ‘sensor.motion_sensor_3de_verdieping_battery’, ‘sensor.zwijntje_battery’, ‘sensor.ipad_maud_battery_level’, ‘sensor.iphone_elke_battery’, ‘sensor.bart_s_iphone_battery_level’, ‘sensor.iphone_maudje_mijn_schatje_battery_level’, ‘sensor.ipad_pro_bart_teuwen_battery_level’, ‘sensor.iphone_maudje_mijn_schatje_battery_level_2’, ‘sensor.bart_s_iphone_battery_level_2’, ‘sensor.cover_living_groot_rechts_battery’, ‘sensor.cover_living_links_groot_battery’, ‘sensor.cover_slaapkamer_m_b_links_battery’, ‘sensor.cover_slaapkamer_m_b_rechts_r_battery’, ‘sensor.cover_slaapkamer_m_b_rechts_l_battery’, ‘sensor.cover_living_midden_links_batterij’, ‘sensor.cover_living_midden_rechts_batterij’]

But if I try to make this into a sensor like this:

- platform: template
  sensors:
    battery_niveau2:
      value_template: >-
          {%- set bat = namespace(data = []) %}
          {%- set batn = namespace(below = []) %}
          {% set bat.data = bat.data + states 
          |selectattr("attributes.device_class","defined")
          |selectattr("attributes.device_class", "search","battery")
          | map(attribute='entity_id')
          |list %}
           {%- for x in bat.data %}
           {%- if states(x) != "unavailable" %}         
          {%- if states(x)|int <= states("input_number.batteryniveau_alarm_3")|int %}   
          {%- set batn.below = batn.below + [ x ] %}
          {%- endif %}  
          {%- endif %}  
          {%- endfor %}
          {{ batn.below}}

then I get a completely different result, being:

[‘sensor.hue_motion_verwarm_1ste_verd_battery’, ‘sensor.motion_sensor_2de_verdieping_battery’, ‘sensor.zwijntje_battery’, ‘sensor.cover_slaapkamer_m_b_rechts_r_battery’, ‘sensor.cover_slaapkamer_m_b_rechts_l_battery’]

Is there anyone who can tell me what I’m missing here, I’ve been working on it for a while but can’t find what I’m doing wrong at all!!

Thanks for every response
Bart