0

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

Jeff-C
  • 77
  • 1
  • 7
  • It seems like you searching for `break` operator. Better to filter your data before rendering. Also try to look this topic [how can i break a for loop in jinja2](https://stackoverflow.com/questions/22150273/how-can-i-break-a-for-loop-in-jinja2) – Etoneja Aug 25 '20 at 01:55
  • break might work... i shall try – Jeff-C Aug 25 '20 at 02:01

1 Answers1

0

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 %}
Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34