Jinja2烧瓶:迭代时使用rowspan两次



我将以下列表传递给jinja2模板通过烧瓶:

yrs = [2016, 2017]
months = [['June'], ['January', 'February']]
names = [[['John', 'Mike']], [['Sara'], ['Steph', 'James']]]

我正在尝试制作一个看起来像这样的表:https://jsfiddle.net/46qqqfef5/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-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>

最新更新