'jinja2 using {if} within {for}

I'm trying to make a template which iterates over a list to check if a string exists. if it does then something happens, if the string isn't in the list, something else should happen. The issue is the result is repeated for all the lines in the list, which i do not want.

e.g.

The list is some simple yaml

LIST:
 - A
 - B
 - C

Jinja looks like


     {% for line in mylist %}
     {% if 'A' in line  %}
     {{ A }} Was found in the list
     {% else %}
     {{ A }} Was not found
     {% endif %}
     {% endfor %}

So when 'A' matches i get this

A Was found in the list
A Was not found
A Was not found

And when 'A' does not match i get this:

A Was not found
A Was not found
A Was not found

Basically i need to stop it iterating over the list and just do one thing if it matches or one thing if it doesn't match

So if 'A' matches i need it to just do A was found

If 'A' doesn't match i need it to just do A was not found



Solution 1:[1]

Use some kind of flag variable:

{% set ns = namespace(found=false) %}

{% for line in mylist %}
    {% if 'A' in line  %}
        {% set ns.found=true %}
    {% endif %}
{% endfor %}

{% if ns.foo %}
    {{ A }} Was found in the list
{% else %}
    {{ A }} Was not found
{% endif %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eziz Durdyyev