Some help on jinja2 looping through a dictionary to get a particular entry

Hi,

I’m struggling with a learning curve on jinja2.
I’m trying to find the favorite currently playing.
As it seems, the only way is to loop through all entries.
But when I do this (in the developer tools) after the loop the variable favo seems to have lost scope (a match was found, but favo is lost somehow).
I’ve tried various things:

  • defining the variable upfront and set it again
  • defining an object upfront, updating it (setattr is not supported?),
    What am I doing wrong? Is there another way?
{% set channel = state_attr('media_player.woonkamer','media_channel') | trim %}
{{ channel }}
{% set ids = state_attr('sensor.sonos_favorites_2','items') %}
{% for id in ids %}
{{ ids[id]==channel }}
{% if channel == (ids[id] | trim) %}
{% set favo = id %}
{% endif %}
{% endfor %}
FAVO:{{ favo }}

You are correct that it is losing scope. You can use namespace to create a variable that is accessible both in the loop and after:

{% set ns = namespace(favo="") %}
{% set channel = state_attr('media_player.woonkamer','media_channel') | trim %}
{{ channel }}
{% set ids = state_attr('sensor.sonos_favorites_2','items') %}
{% for id in ids %}
{{ ids[id]==channel }}
{% if channel == (ids[id] | trim) %}
{% set ns.favo = id %}
{% endif %}
{% endfor %}
FAVO:{{ ns.favo }}
1 Like

Your statement is totally correct. The variable is only available in the loop and not outside. Take this as an example:

            {% set levels = namespace(lvl=[]) %}  
            {% for height in value_json.flooddata %}
              {% set levels.lvl = levels.lvl + [height.level] %}
            {% endfor %}
            {{levels.lvl | max }}

You use a namespaced variable outside the loop and you can then manipulate it inside the loop and get the value after the loop is finished. So levels.lvl becomes a list of all levels and then this only gets the max value in that list.

And as I submitted this, I see someone answered the same!

1 Like

namespaces, thnx probably going to bump my head that it took me this long too find those :sweat_smile:
Was already considering to do a k-v remapping somewhere to get around this loop.
thnx!