Gio*_*lia 2 django django-templates
我有一个值列表,我想在django的模板中显示.
列表或多或少是这样的:
199801 string1
199802 string2
199904 string3
200003 string4
200011 string5
Run Code Online (Sandbox Code Playgroud)
其中第一列是YYYYMM形式的日期,第二列是通用字符串
列表按日期desc排序
我想要创建的是按年份分组的stringx列表,如下所示:
1998 string1, string2
1999 string3
2000 string4, string5
Run Code Online (Sandbox Code Playgroud)
我看了一下文档,我认为我唯一需要的是创建变量的方法来存储我打印的"去年",所以我可以这样做:
if current_value.year != last_year
#create a new row with the new year and the string
else
#append the current string to the previous one
Run Code Online (Sandbox Code Playgroud)
我认为我发现的唯一方法是编写自定义模板标签并让它存储变量和值......但在开始编写代码之前我想知道是否有更简单的方法!
总是做这样的事情,模板系统不是为这样的操作而设计的.此外,实现这一点要困难得多 - 我想到的最好的想法是创建一个过滤器.然而,这将是疯狂的 - 你只需一次使用就可以创建一个非常具体的过滤器.在视图中很容易实现:
last = None
result = []
for year, value in tuples:
if year[0:4] == last:
result[-1].append(value)
else:
result.append([value])
last = year[0:4]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |