【问题标题】:jinja2 flask: using rowspan twice while iteratingjinja2烧瓶:迭代时使用rowspan两次
【发布时间】:2017-03-10 01:38:36
【问题描述】:

我正在通过烧瓶将以下列表传递给 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 列表的结构有关。

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    先试试这个(未测试)。看来您滥用了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>
    

    【讨论】:

    • 我收到以下错误:“UndefinedError: 'list object' has no attribute 'values'”。看来我需要弄清楚如何计算每年的项目。访问父循环的好技巧 - 应该可以!
    • @jcmetz21 只需删除.values()。我的错。
    • 新网址现在是this
    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多