I’m trying to create a template sensor that looks for the best quality in a list of YouTube videos.
The issue I’m having is that only the last item in the list is used. I’m not sure how to select the best value or end the loop once I get a result I’m happy with.
I’m thinking now that I can’t use a ‘for’ loop for this, and I need to look at the whole list without using a loop, but I’m not sure if this is correct, or where to look next.
{% set videos = namespace(search=[]) %}
{% set search = state_attr('sensor.rss_search_result', 'titles') %}
{% set input = state_attr('input_text.rss_search', 'pattern') %}
{% for item in search %}
{%- if input in item %}
{%- if ' 720p ' in item %}
{% set videos.search = [item] %}
{%- endif %}
{%- if ' 1080p ' in item %}
{% set videos.search = [item] %}
{%- endif %}
{%- if ' 2160p ' in item %}
{% set videos.search = [item] %}
{%- endif %}
{%- endif %}
{% endfor %}
{{ videos.search }}
Heya, from what I understand you’re trying to append to an empty list you created. But then instead of appending to the list, you are replacing it with the individual item in each loop. This might be, why you are left with only the last checked item.
I have a sensor looking for the earliest time of extreme weather warning starts by adding each to a list and then returning the minimum. My approach is similar to yours but keeps the already defined list and adds each new item. Hope this helps you adjust yours successfully.
{% if states('sensor.dwd_weather_warnings_current_warning_level')|int(0) > 0 %}
{%- set warning = namespace(start=[]) -%}
{%- for i_warning in range(state_attr('sensor.dwd_weather_warnings_current_warning_level', 'warning_count')|int(0)) -%}
{%- set warning.start = warning.start + [state_attr('sensor.dwd_weather_warnings_current_warning_level', 'warning_' ~ (i_warning+1) ~ '_start')] -%}
{%- endfor -%}
{{ min(warning.start) }}
{% else %}
{{ '-' }}
{% endif %}