如何使用嵌套循环创建表
How to use nested loops to create tables
我有两个列表,我想使用 jinja 和 for 循环创建一个 table。使用一个列表和一个 for 循环没有问题。
<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>
创建
但是,当我尝试从另一个列表中引入另一个 for 循环时,就会发生这种情况。
<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>
这是我理想的结果。我试图弄乱循环结束,但无法正确显示它。
有几种方法可以解决这个问题。
一种解决方案是预先将两个列表与 zip 组合。
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>
但您也可以使用当前索引来访问值。
<table>
{% for a,b in list_1 %}
<tr>
<td>a</td>
<td>b</td>
<td>{{ list_2[loop.index0] }}</td>
</tr>
{% endfor %}
</table>
我有两个列表,我想使用 jinja 和 for 循环创建一个 table。使用一个列表和一个 for 循环没有问题。
<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>
创建
但是,当我尝试从另一个列表中引入另一个 for 循环时,就会发生这种情况。
<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>
这是我理想的结果。我试图弄乱循环结束,但无法正确显示它。
有几种方法可以解决这个问题。
一种解决方案是预先将两个列表与 zip 组合。
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>
但您也可以使用当前索引来访问值。
<table>
{% for a,b in list_1 %}
<tr>
<td>a</td>
<td>b</td>
<td>{{ list_2[loop.index0] }}</td>
</tr>
{% endfor %}
</table>