Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.5k views
in Technique[技术] by (71.8m points)

flask - How to use nested loops to create tables

I have two lists, that I want to create a table with using jinja and for loops. Using one list and one for loops there are no issues.

<table>
    <tr>
        <th>Customer</th>
        <th>Product</th>
        <th>QTY</th>
    </tr>

    {% for i,e in list_2 %}
    <tr>
        <td>{{ i }}</td>
        <td>{{ e }}</td>
    </tr>
    {% endfor %}
 </table>

Creates

enter image description here

However, when I try to introduce another for loop from another list this happens.

<table>
    <tr>
        <th>Customer</th>
        <th>Pro</th>
        <th>QTY</th>
    </tr>

    {% for i,e in list_2 %}
    <tr>
        <td>{{ i }}</td>
        <td>{{ e }}</td>
        {% for i in qtyyyy %}
        <td>{{ i }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

enter image description here

This is my ideal result. I have attempted to mess with the loops ending, but have not been able to correctly display it.

enter image description here

question from:https://stackoverflow.com/questions/65600970/how-to-use-nested-loops-to-create-tables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several ways you can solve the problem.
One solution would be to combine the two lists with zip beforehand.

list_1 = [
  ('(Retail)', 'Example'), 
  ('(1)(Distributor)', 'Example'), 
  ('(Ditributor)', 'Example'), 
  ('False', 'Example')
]
list_2 = [35.0, 147.0, 50.0, 180.0]
list_3 = [a + (b,) for a,b in zip(list_1, list_2)]
<table>
{% for a,b,c in list_3: %}
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
{% endfor %}
</table>

But you can also use the current index to access the values.

<table>
  {% for a,b in list_1 %}
    <tr>
      <td>a</td>
      <td>b</td>
      <td>{{ list_2[loop.index0] }}</td>
    </tr>
  {% endfor %}
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...