python – 在jinja2中循环一个元组

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

我想制作一个这样的HTML

<li class="year">
    <a href="#">2013</a>
    <ul>
    <li class="month">
        <a href="#">11</a>
        <ul>
            <li class="day">01</li>
            <li class="day">02</li>
            <li class="day">03</li>
            ...
        </ul>
    </li>
    <li class="month">
        <a href="#">12</a>
        <ul>
            <li class="day">01</li>
            <li class="day">02</li>
            ...
        </ul>
     </li>
     </ul>
</li>

我已经尝试了一天,但还没找到方法.是否有捷径可寻 ?或者我应该更改数据结构?

最佳答案 您应该更改数据结构.像这样的复杂数据处理属于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 = [[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))

一般来说,任何开头“我如何让我的模板系统在这个结构中输出数据”的问题的答案是“在该结构中提供数据”.

点赞