【问题标题】:How to create unknown numbers of HTML tables如何创建未知数量的 HTML 表格
【发布时间】:2018-02-20 01:29:14
【问题描述】:

我正在尝试使用 Django-Python 呈现表格。假设我有从 A-Z 开始的姓氏记录。现在,我想根据每个字母创建一个表,并将所有具有第一个字母姓氏的人放在他们自己的表上。

EX:
TABLE A Last names
  Adams
  Anderson

TABLE B Last names
  Barnes
  Bill
  Brandon 

TABLE J Last names
  Jackson
  Johnson 

etc….   ## this is the output I want to achieve

HTML:

  <legend>Customers</legend>    
    <table>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
      <tr>
      {% for idx in people %}
        <td>{{ idx.0 }}</td>
        <td>{{ idx.1 }}</td>
      </tr>
      {% endfor %}
    </table>

views.py

def index(request):
    context = {
        "people": People.objects.all()
    }
    return render(request, 'index.html', context)

我可以轻松渲染它。但是,我试图通过创建多达 26 个表来根据他们的姓氏将每个人分开。我希望它们都出现在同一个 html 页面中,但相应地用表格分隔。我不知道数据库中有多少个字母,并且我试图避免对带有 A-Z 标题的表进行硬编码。这是因为在我的应用程序中,有可能在 26 个字母中,我只有 5 个可用字母。使用 {% tags %} 在 html 中循环非常有用。

我一直在尝试在 html 的循环中创建一个表格,但我得到了有趣的结果。谁能帮帮我?

非常感谢!

【问题讨论】:

    标签: python html django python-2.7


    【解决方案1】:

    您需要{% regroup %} 标签。

    {% regroup people by firstname.0 as initials %}
    
    {% for initial in initials %}
        <h2>TABLE {{ initial.grouper }} LAST NAMES</h2>
        <table>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
          </tr>
          <tr>
          {% for person in initial.list %}
            <td>{{ person.firstname }}</td>
            <td>{{ person.lastname }}</td>
          </tr>
          {% endfor %}
        </table>
    {% endfor %}
    

    注意,您的视图需要按姓氏对人员进行排序才能正常工作:

    context = {
        "people": People.objects.all().order_by('lastname')
    }
    

    【讨论】:

    • 嗨丹尼尔,谢谢!我以前从未使用过这个重组标签。我现在试一试。再次感谢:)
    猜你喜欢
    • 2014-09-15
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2017-03-17
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多