Django 模板显示嵌套的年份和日期列表
Django Template To Display Nested List Of Years And Dates
我认为以下代码...
dates = Article.objects.dates('date', 'month').order_by('-date')
生成以下日期列表...
[
datetime.date(2016, 3, 1), datetime.date(2016, 1, 1),
datetime.date(2016, 1, 1), datetime.date(2015, 2, 1),
datetime.date(2015, 2, 1), datetime.date(2015, 1, 1),
datetime.date(2015, 1, 1)
]
我现在需要使用以下标记创建嵌套列表...
<ul class="news-selector">
<li><a href="todo">Year</a>
<ul>
<li><a href="todo">Month</a></li>
</ul>
</li>
</ul>
我正在努力使用 'changeif' 或 'regroup' 有人知道如何使用 django 模板系统来管理它吗?
这会给你列表
<ul class="news-selector">
{% for y in dates %}
{% ifchanged y.year %}
<li><a href="todo">{{y|date:'Y'}}</a>
<ul>
{% for m in dates %}
{% if m|date:'Y' == y|date:'Y' %}
<li><a href="todo">{{ m|date:'M' }}</a></li>
{% endif %}
{% endfor %}
</ul>
</li>
{% endifchanged %}
{% endfor %}
</ul>
我现在看到它在 {% if m|date:'Y' == y|date:'Y' %} 行中,我已经设法通过准备来减少循环视图中的数据更好一些。
date_list = Article.objects.dates('date', 'month', order='DESC')
dates = []
for date in date_list:
dates.append({
'year': str(date.year).rjust(4, '0'),
'month': str(date.month).rjust(2, '0'),
'month_name': date.strftime("%B")
})
并且在模板中...
{% regroup dates by year as year_dates %}
<ul class="news-selector">
{% for year in year_dates %}
<li><a href="todo">{{year.grouper}}</a>
<ul>
{% for month in year.list %}
<li><a href="{% url 'news_filter' month.year month.month %}">{{month.month_name}}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
似乎可行,但可能还可以改进。
我认为以下代码...
dates = Article.objects.dates('date', 'month').order_by('-date')
生成以下日期列表...
[
datetime.date(2016, 3, 1), datetime.date(2016, 1, 1),
datetime.date(2016, 1, 1), datetime.date(2015, 2, 1),
datetime.date(2015, 2, 1), datetime.date(2015, 1, 1),
datetime.date(2015, 1, 1)
]
我现在需要使用以下标记创建嵌套列表...
<ul class="news-selector">
<li><a href="todo">Year</a>
<ul>
<li><a href="todo">Month</a></li>
</ul>
</li>
</ul>
我正在努力使用 'changeif' 或 'regroup' 有人知道如何使用 django 模板系统来管理它吗?
这会给你列表
<ul class="news-selector">
{% for y in dates %}
{% ifchanged y.year %}
<li><a href="todo">{{y|date:'Y'}}</a>
<ul>
{% for m in dates %}
{% if m|date:'Y' == y|date:'Y' %}
<li><a href="todo">{{ m|date:'M' }}</a></li>
{% endif %}
{% endfor %}
</ul>
</li>
{% endifchanged %}
{% endfor %}
</ul>
我现在看到它在 {% if m|date:'Y' == y|date:'Y' %} 行中,我已经设法通过准备来减少循环视图中的数据更好一些。
date_list = Article.objects.dates('date', 'month', order='DESC')
dates = []
for date in date_list:
dates.append({
'year': str(date.year).rjust(4, '0'),
'month': str(date.month).rjust(2, '0'),
'month_name': date.strftime("%B")
})
并且在模板中...
{% regroup dates by year as year_dates %}
<ul class="news-selector">
{% for year in year_dates %}
<li><a href="todo">{{year.grouper}}</a>
<ul>
{% for month in year.list %}
<li><a href="{% url 'news_filter' month.year month.month %}">{{month.month_name}}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
似乎可行,但可能还可以改进。