-1

I am making web service with flask, and having trouble with jinja2 'for loop in for loop'. I made 'for loop in for loop' but it is not returning right. for example. (I made it simple because original code is more complex)

numbers1 = {{"value":1},{"value":2},{"value":3}}
numbers2 = {{"value":1},{"value":2},{"value":3}}

    {% for num1 in numbers1 %}
            {{num1.value}}
            {% for num2 in numbers2 %}
                {% if num2.value == num1.value %}
                    {{num2.value}}
                {% else %}
                {% endif %}
            {% endfor %}
        {% endfor %}

and the result was look like this

11 2 3

but I was trying to get result like this

11 22 33

I tried several different ways, but I could not solve it. Really think you if you could help me. Thanks

bluesky
  • 55
  • 1
  • 7

2 Answers2

0

Change num1 to num, and then try if it works!

Tushar
  • 1,076
  • 1
  • 9
  • 11
  • opps sorry~ num is num1. I edited. the point is that second for loop is not working as I expected in jinja2 – bluesky Aug 25 '20 at 08:30
0

It is working as expected with:

from jinja2 import Template

tmpl = Template("{% for num1 in numbers1 %}{{num1.value}}{% for num2 in numbers2 %}{% if num2.value == num1.value %}{{num2.value}}{% else %}{% endif %}{% endfor %}{% endfor %}")

print(tmpl.render(
    numbers1 = [{"value":1},{"value":2},{"value":3}],
    numbers2 = [{"value":1},{"value":2},{"value":3}]
))

Your issue should be elsewhere.

Jona
  • 1,218
  • 1
  • 10
  • 20