Template: if / else inside loop

Hi, I’m trying to calculate the average of 3 sensors. To avoid breaking it I need to use only the sensor that are not “unknown” since I noticed sometimes they go ‘unknown’ for a bit.
So the plan is to loop over the sensor, placed in an array. For each that is available I should add it to a variable, and count how many sensors are not ‘unknown’ . At the end divide the sum of the sensor values by the count of the ‘known’ sesnros.

Here’s my code and it’s not working, I guess some syntax errors with the code.

{% set val = (states('sensor.sensor_22851_pm10'), states('sensor.sensor_40645_pm10'), states('sensor.sensor_50128_pm10')) %}

{% set counter = 0 %}
{% set pmVal = -1 %}
{% for v in val %}
{% if v != 'unknown' -%} pmVal += (v | float),  counter += 1
{% endif %}
{% endfor %}
{{ pmVal / counter }}
{{ ['sensor.sensor_22851_pm10', 'sensor.sensor_40645_pm10', 'sensor.sensor_50128_pm10'] | select('has_value') | map('states') | map('float') | average }}
1 Like