我通过烧瓶将以下列表传递给 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句