在Jinja2中遍历一个元组

 手机用户2502905117 发布于 2023-02-13 15:29

我有一个格式为['DD','MM','YYYY']的日期列表,并将其保存到名为listdates [[''DD','MM','YYYY'],['DD', 'MM','YYYY']]

我想做一个这样的HTML

  • 2013
    • 11
      • 01
      • 02
      • 03
      • ...
    • 12
      • 01
      • 02
      • ...
  • 我已经尝试了一天,但没有找到方法。是否有捷径可寻 ?还是应该更改数据结构?

    1 个回答
    • 您应该更改数据结构。像这样的复杂数据处理属于Python,而不属于模板。您可能会在Jinja 2中找到破解它的方法(尽管在Django的模板中可能没有)。但是您不应该这样做。

      而是创建一个嵌套的数据结构

      dates = [[d1, m1, y1], ..., [dn, mn, yn]]
      datedict = {}
      for d, m, y in dates:
          yeardict = datedict.setdefault(y, {})
          monthset = yeardict.setdefault(m, set())
          monthset.add(d)
      
      nested_dates = [(y, list((m, sorted(days))
                               for m, days in sorted(yeardict.items())))
                      for y, yeardict in sorted(datedict.items())]
      

      所以如果dates开始为

      dates = [[1, 2, 2013], [5, 2, 2013], [1, 3, 2013]]
      

      nested_dates 最终会变成

      [(2013, [(2, [1, 5]), (3, [1])])]
      

      所以你可以做

      {% for year in nested_dates %}
          <li class="year">
              <a href="#">{{year.0}}</a>
              <ul>
              {% for month in year.1 %}
                  <li class="month">
                      <a href="#">{{month.0}}</a>
                      <ul>
                      {% for day in month.1 %}
                          <li class="day">{{day}}</li>
                      {% endfor %}
                      </ul>
                  </li>
              {% endfor %}
              </ul>
          </li>
      {% endfor %}
      

      注意:如果您希望以后对代码或其他程序员有意义,那么列表理解将限制您应该在列表理解中进行的工作。因此,您可以将其更清楚地写为:

      nested_dates = []
      for y, yeardict in sorted(datedict.items()):
          yearlist = []
          for m, days in sorted(yeardict.items()):
              yearlist.append((m, sorted(days)))
          nested_dates.append((y, yearlist))
      

      通常,对任何以“如何使我的模板系统以这种结构输出数据”开头的问题的答案是“在该结构中提供数据”。

      2023-02-13 15:31 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有