[英]jinja2 flask: using rowspan twice while iterating
我通过烧瓶将以下列表传递给Jinja2模板:
yrs = [2016, 2017]
months = [['June'], ['January', 'February']]
names = [[['John', 'Mike']], [['Sara'], ['Steph', 'James']]]
我正在尝试制作一个看起来像这样的表: https : //jsfiddle.net/46qqfef5/4/
这是我拼凑成的不成功的Jinja2代码:
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for yr_index in range(yrs | count) %}
{% for month_index in range(months[yr_index] | count) %}
{% for name_index in range(names[yr_index][month_index] | count) %}
<tr>
{% if loop.first %}
{% if loop.first %}
<td rowspan="{{ names[yr_index] | count }}">{{ yrs[yrs_index] }}</td>
{% endif %}
<td rowspan="{{ names[yr_index][month_index] | count }}">{{ months[yr_index][month_index] }}</td>
{% endif %}
<td>{{ names[yr_index][month_index][name_index] }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
<div>
因此,我基本上只是想将这些列表解压缩到一个有组织的表中,但是rowspan
属性给我带来了很多麻烦。 任何提示将不胜感激,即使它与更改python列表的结构有关。
首先尝试一下(没有测试)。 似乎您滥用了loop.first
(您有嵌套的循环,实际上不能依赖loop.first
)。 而且,在检索计数之前,您还需要展平names[yr_index]
列表。
考虑阅读以下内容: http : //jinja.pocoo.org/docs/dev/tricks/#accessing-the-parent-loop 。
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for yr in yrs %}
{% set yr_loop = loop %}
{% for month in months[loop.index0] %}
{% set month_loop = loop %}
{% for name in names[yr_loop.index0][loop.index0] %}
<tr>
{% if loop.first %}
{% if month_loop.first %}
<td rowspan="{{ names[yr_loop.index0]|sum(start=[])|count }}">{{ yr }}</td>
{% endif %}
<td rowspan="{{ loop.length }}">{{ month }}</td>
{% endif %}
<td>{{ name }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
<div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.