Try a loop in an automation

Hello everyone,

I haven’t been working with HA for that long and I’m trying out everything.

I now have the following problem:

I have a list of names and try each part of this list in an equation and if the equation is “True” some action needs to happen. Try this with a loop to shorten my code and give it a try, but it won’t work!!

Does anyone have a good solution for this?

My code is as follows:

{% for Naam in ("maud", "bart","elke","stijn") %}
  {% if states("variable.verjaardag_" + Naam).split()[0:2]|join(' ') ==
      now().strftime('%d') + ' ' + states.sensor.maand.state %}
        {% set N= state_attr("variable.verjaardag_" + Naam,"friendly_name").split()[-1] %}
      
    {% endif %}
    
    {{N}}
     
{% endfor %}

Sorry for any serious mistakes and less good English, but for me this is a learning process!
Thanks for every tip and help
Greetings Bart

What you have posted is a template that will print a series of values… it is not an automation.

It would be helpful if you describe what your goal for the template is and post the automation that it is to be used in. Additionally, when using a custom setup like the variables integration you should show an example of the state and attributes of you entities (for privacy this can be a fake name and birthday, as long as it shares the same structure and formats as the entities you are trying to work with)

From what you have posted it looks like you have a set of variable entities, each of which have a state representing a person’s birthday. You seem to be trying to test whether today matches any of those dates and then outputting the name of the person.

Thanks for your response!!

This is full automation

alias: AAA Verjaardag en feestdag
description: ""
trigger:
  - platform: state
    entity_id:
      - input_boolean.testknop
condition:
  - condition: template
    value_template: >-
      {% for Naam in ("maud", "bart","elke","stijn") %}
        {% if states("variable.verjaardag_" + Naam).split()[0:2]|join(' ') ==
          now().strftime('%d') + ' ' + states.sensor.maand.state %}
          {% set N= state_attr("variable.verjaardag_" + Naam,"friendly_name").split()[-1] %}
      
        {% endif %}
    
        {{N}}
     
        {% endfor %}
action:
  - service: script.berichten
    data: 
      call_Feestdag: 1
      Welke_Output: Ios Bart
      Welke_Naam: 
mode: single

What format is the date that is returned as the state of your variable entities and sensor.maand?

You can copy the following into the Template tool then share the result so we can figure out where the issue is:

{{ state_attr('variable.verjaardag_stijn', 'friendly_name') }}

{{ states('variable.verjaardag_stijn') }}

{{ states('sensor.maand') }}

Your N variable only exists inside the if statement. To expose it outside, you need to use a namespace:

{% set ns = namespace(N="") %}
{% for ... %}
  {% if ... %}
    {% set ns.N = ... %}
  {% endif %}
  {{ ns.N }}
{% endfor %}