Template Evaluation to False instead of True :-(

Hi all,

I have a very basic question, but Copilot couldn’t help either :frowning:

I have this test code:

{% set agenda = {"calendar.test":{"events":[{"start":"2024-12-13","end":"2024-12-16","summary":"Christmas Market"},{"start":"2024-12-14","end":"2024-12-16","summary":"Christmas Market New York"},{"start":"2024-12-14T08:00:00+01:00","end":"2024-12-14T18:30:00+01:00","summary":"Christmas Market London","location":"Market Square"},{"start":"2024-12-14T16:00:00+01:00","end":"2024-12-14T18:30:00+01:00","summary":"Christmas Market Berlin"}]}} %}

{% set result = false -%}
{% for event in agenda["calendar.test"]["events"] -%}
  {% set EINTRAG = event['summary'] -%}
  {% if 'Holidays' in EINTRAG -%}
    {% set result = true -%}
    {{ 'Holidays: '+EINTRAG -}}
  {% elif 'Christmas Market' in EINTRAG -%}
    {% set result = true -%}
    {{ 'Christmas market: '+EINTRAG+'\n' -}}
  {% endif -%}
{% endfor -%}
{{ result }}
Christmas market: Christmas Market
Christmas market: Christmas Market New York
Christmas market: Christmas Market London
Christmas market: Christmas Market Berlin
False

I don’t get it. Whatever I do, I end up with the template evaluating to ‘False’ (this is a string, but if I omit all the debugging messages, it will still evaluate to $false)

What am I missing here?

Update: Script Syntax - Home Assistant.
Huh, so this is expected. But how to dodge this and properly set the variable to $true?

Use a namespace:

{% set ns = namespace(result=false) -%}
{% for event in agenda["calendar.test"]["events"] -%}
  {% set EINTRAG = event['summary'] -%}
  {% if 'Holidays' in EINTRAG -%}
    {% set ns.result = true -%}
    {{ 'Holidays: '+EINTRAG -}}
  {% elif 'Christmas Market' in EINTRAG -%}
    {% set ns.result = true -%}
    {{ 'Christmas market: '+EINTRAG+'\n' -}}
  {% endif -%}
{% endfor -%}
{{ ns.result }}

EDIT: Corrected typo in first line.

If you only need the end result and not the print out of the events, you can avoid the loop completely:

{{ agenda["calendar.test"]["events"]
| selectattr('summary', 'match', 'Holidays|Christmas Market')
| list | count > 0 }}
1 Like

Ah, thanks mate! I found that solution here too, Variable scope in automation - not clear what's wrong - #5 by WallyR, but didn’t understand how to apply this properly <3

Update: I had to add this to set the results to false if the loop did not return true

{% set ns = namespace(results=false) -%}
{% set ns.result = false -%}