Home > OS >  Problem setting the Jinja variable during iteration in flask
Problem setting the Jinja variable during iteration in flask

Time:10-10

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.

CodePudding user response:

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>
  • Related