Return more than one value in template, set in for-loop

Hello!

I have a code for a variable like this:

    temp: >
              {% set result = {'current': 0, 'target': 0} %}
              {% set thermostats_array = expand(thermostats) %}            
                {% for thermostat in thermostats_array %}
                  {% set result = {'current': 12, 'target': 34} %}
                {% endfor %}
              {{ result }}

This is only the stripped testing code focused on the problem, in the real code, some more calculations are done.

The thing is I want to be able to return more than one value accessing them with:
temp.current
temp.target

The problem is that “result” in the for-loop only exists in the for-loop which makes this code return:
temp.current = 0
temp.target = 0

How can I set result.current and result.target inside the for-loop and preserve it to return it at the end?

You need to use a namespace.

{%- set ns = namespace( c_list = [] ) -%}
{% for c in states.climate %}
  {% set ns.c_list = ns.c_list + [{c.name:{"temp": c.attributes.temperature, "current_temp": c.attributes.current_temperature}}] %}
{% endfor %}
{{ ns.c_list }}
1 Like

Thanks for your reply! This works, even with a dictionary as well:

 {% set ns = namespace( c_dict = {'current': 0, 'target': 0} ) %}
 {% set thermostats_array = expand(thermostats) %}            
 {% for thermostat in thermostats_array %}
   {% if ... %}
     {% set ns.c_dict = {'current': 12, 'target': 34} %}
   {% endif %}
 {% endfor %}
 {{ ns.c_dict }}

Won’t this overwrite the value in the loop of you loop more than one thermostat?