-1

My code for HTML is following:

<div class = "methods">
        {% set j = 1 %}
        {% for i in range (4) %}
        <div class = "mrow">
            <div class = "mrow1">
                <div class = "mrow11">
                <img src = "static/images/metodo{{ listofitems[j] }}.png">
                </div>
                <div class = "mrow2 gold">
                    MÉTODO
                </div>
            </div>
            <div class = "mrow1">
                <div class = "mrow11">
                <img src = "static/images/metodo{{ listofitems[j+1] }}.png">
                                    {% set j = j + 2 %}
                                    {{ j }}
                </div>
                <div class = "mrow2 gold">
                    MÉTODO
                </div>
            </div>
        </div>
        {% endfor %}
</div>

variable which I passed from flask is listofitems = [0, 1, 2, 3, 4, 5, 6, 7] and images are 'metodo1.png', 'metodo2.png' etc. It makes src attribute for all images 'metodo1.png' and 'metodo2.png', ignoring the increment i did on j. Only time it increases j is the first time. I want to have total of 8 images and each one dynamically changes source into 1...8. With {{ j }} line it prints 3 under every second image, never increasing it further.

Thank you very much in advance.

h20002000
  • 73
  • 7

1 Answers1

2

Instead of assigning a separate variable, isn't this possible within the for loop itself? I'm assuming you want the loop to execute 4 times and the two consecutive images should be displayed in each iteration. This is what's done here by modifying the for loop to meet that criteria.

<div class = "methods">
        {% for i in range (1, 9, 2) %}
        <div class = "mrow">
            <div class = "mrow1">
                <div class = "mrow11">
                <img src = "static/images/metodo{{ listofitems[i] }}.png">
                </div>
                <div class = "mrow2 gold">
                    MÉTODO
                </div>
            </div>
            <div class = "mrow1">
                <div class = "mrow11">
                <img src = "static/images/metodo{{ listofitems[i+1] }}.png">
                                    {{ i }}
                </div>
                <div class = "mrow2 gold">
                    MÉTODO
                </div>
            </div>
        </div>
        {% endfor %}
</div>
vnk
  • 1,060
  • 1
  • 6
  • 18
  • Oh, that works, thanks. By the way I found the answer, apparently there was scoping problem so I need to turn j into an object - https://stackoverflow.com/questions/7537439/how-to-increment-a-variable-on-a-for-loop-in-jinja-template/49699589#49699589 – h20002000 Oct 09 '21 at 13:20