首页 > 解决方案 > Jinja2 loop creating duplicates

问题描述

I am trying to create a table using data from a few arrays that I have for my Flask webapp.

I am using two loops -- first to loop through the variables to create the rows; second to loop through the array itself to get the different positions. This works for the most part but it is looping too much? My results are the same thing just 3 times.

<table id="example-datatable" class="table table-bordered table-hover">
<thead>
    <tr>
        <th>Item</th>
        <th>Quantity</th>
        <th>Price</th>
        <th>Discount %</th>
    </tr>
</thead>

<tbody>
    {% for record in invoice %}
    {% set length = (invoice | length)-1 %}
    {% for i in range(0, length) %} 
    <tr>
        <td>{{invoice["fields"]["Account item codes"][i]}}</td>
        <td>{{invoice["fields"]["Account item quantities"][i]}}</td>
        <td>{{invoice["fields"]["Account item prices"][i]}}</td>
        <td>{{invoice["fields"]["Account item discount %s"][i]}}</td>
    </tr>
    {% endfor %}
    {% endfor %}
    </tbody>

These are the results I get. It's correct, but just replicating three times and not just once.

Results

I am to the point now where I think I have looked at it so much that I am blind to the problem.

标签: pythonloopsflaskhtml-tablejinja2

解决方案


能够通过取出一个循环来修复它......愚蠢的修复。但很高兴把它修好!

编辑代码:

<table id="example-datatable" class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Discount %</th>
                                    </tr>
                                </thead>

                                <tbody>
                                    {% set length = (invoice | length)-1 %}
                                    {% for i in range(0, length) %} 
                                    <tr>
                                        <td>{{invoice["fields"]["Account item codes"][i]}}</td>
                                        <td>{{invoice["fields"]["Account item quantities"][i]}}</td>
                                        <td>{{invoice["fields"]["Account item prices"][i]}}</td>
                                        <td>{{invoice["fields"]["Account item discount %s"][i]}}</td>
                                    </tr>
                                    {% endfor %}
                                    </tbody>
                            </table>

推荐阅读