Setting a variable within a template using `{% if %}` & continue testing

I know the following doesn’t work, but is there a way that I can I can set a variable (answer) within a template?

Is there a batter way to do this? …I am trying to find out what the highest (of the 6 possible) scheduled temperatures is. Note that not every temp is scheduled.

- name: "Heating max sched temp"
  state: >
    {% set sched1 = states('input_boolean.heating_1_scheduled') %}
    {% set sched2 = states('input_boolean.heating_2_scheduled') %}
    {% set sched3 = states('input_boolean.heating_3_scheduled') %}
    {% set sched4 = states('input_boolean.heating_4_scheduled') %}
    {% set sched5 = states('input_boolean.heating_5_scheduled') %}
    {% set sched6 = states('input_boolean.heating_6_scheduled') %}

    {% set temp1 =  states('input_number.heating_1_temp')|float %}
    {% set temp2 =  states('input_number.heating_2_temp')|float %}
    {% set temp3 =  states('input_number.heating_3_temp')|float %}
    {% set temp4 =  states('input_number.heating_4_temp')|float %}
    {% set temp5 =  states('input_number.heating_5_temp')|float %}
    {% set temp6 =  states('input_number.heating_6_temp')|float %}
    
    {% if sched1 == 'on' %} {% then set answer == temp 1 %}
    {% if sched2 == 'on' and (temp2 > answer) set answer = temp2 %}
    {% if sched3 == 'on' and (temp3 > answer) set answer = temp3 %}
    {% if sched4 == 'on' and (temp4 > answer) set answer = temp4 %}
    {% if sched5 == 'on' and (temp5 > answer) set answer = temp5 %}
    {% if sched6 == 'on' and (temp6 > answer) set answer = temp6 %}
    {{ answer }}

edit: I guess I can do this using an automation.

Maybe…

{% set ns = namespace( max = 0) %} 
{% for r in range(1,7) -%}
 {% if states('input_boolean.heating_' ~ r ~ '_scheduled') == "on" and states('input_number.heating_' ~ r ~ '_temp')|float > max %}
  {%- set ns.max = states('input_number.heating_' ~ r ~ '_temp')|float %}
 {%- endif %}
{%- endfor %}

{{ ns.max }}
2 Likes

Brilliant!

there was one typo…

 {% if states('input_boolean.heating_' ~ r ~ '_scheduled') == "on" and states('input_number.heating_' ~ r ~ '_temp')|float > max %}
                                                                                                                             ^ns.max

…but I really appreciate the guidance. I need to go and learn what the heck namespace() is now!

Also, may I ask why you use -%} in line 2 at the end?

Review the “Scoping Behavior” section of the following documentation.

https://jinja.palletsprojects.com/en/stable/templates/#assignments

1 Like

The {%- and -%} syntax in Jinja2 is used to control whitespace handling. Specifically:

  • {%- removes whitespace (including newlines) before the statement.
  • -%} removes whitespace (including newlines) after the statement.
1 Like

thanks, both!