如何反转 django 模板中的列表?
How to reverse the list inside django template?
我有一个列表,我想通过在 django-html 模板中取消排序,
我该怎么做?
这是我的模板代码
{% for unique_date in unique_dates %}
<th>{{unique_date}}</th>
{% endfor %}
这是我的视图文件
unique_dates = list({a.date for a in attendances})
unique_dates.sort()
您可以将其反向排序:
unique_dates = sorted({a.date for a in attendances}<strong>, reverse=False</strong>)
# no extra sort needed
因此,这会将 a.date
个项目按 反向 顺序排序,因此最大(最新)的排在最前面,最小(最早的)排在最后。
另一种方法是使用 {% for … in … reversed %}
[Django-doc]:
{# rendering in reverse #}
{% for unique_date in unique_dates <strong>reversed</strong> %}
<th>{{ unique_date }}</th>
{% endfor %}
我有一个列表,我想通过在 django-html 模板中取消排序, 我该怎么做?
这是我的模板代码
{% for unique_date in unique_dates %}
<th>{{unique_date}}</th>
{% endfor %}
这是我的视图文件
unique_dates = list({a.date for a in attendances})
unique_dates.sort()
您可以将其反向排序:
unique_dates = sorted({a.date for a in attendances}<strong>, reverse=False</strong>)
# no extra sort needed
因此,这会将 a.date
个项目按 反向 顺序排序,因此最大(最新)的排在最前面,最小(最早的)排在最后。
另一种方法是使用 {% for … in … reversed %}
[Django-doc]:
{# rendering in reverse #}
{% for unique_date in unique_dates <strong>reversed</strong> %}
<th>{{ unique_date }}</th>
{% endfor %}