2012-10-06 159 views
4

我想按月份/年将Jinja中的日期/时间列表分组。这是我现在所拥有的代码:Jinja2按月份/年组

{% for group in EventsList|groupby('date') %} 
     <b>{{group.grouper}}</b><br /> 
     {% for event in group.list %} 
      <i>{{event.title}}</i> 
     {% endfor %} 
    {% endfor %} 

但问题是,它目前的具体日期群体。我想按月份/年份(即2011年1月,2011年2月等)进行分组。

用Python代替它会更有效吗?

谢谢!

回答

6

你可以先groupby('date.year')然后groupby('date.month')。

{% for year, year_group in EventsList|groupby('date.year') %} 
    {% for month, list in year_group|groupby('date.month') %} 
     <b>{{ month }} {{ year }}</b><br /> 
     {% for event in list %} 
      <i>{{event.title}}</i> 
     {% endfor %} 
    {% endfor %} 
{% endfor %} 
+0

谢谢!想知道,是否可以将{{月}}格式化为长格式(即10月)而不是数字格式(即10)。我还在考虑一种替代方法,我只需在数据存储中创建长表格月份/年的另一列(即“2012年10月”)......但这样做效率很低。 – iceanfire

+0

您可以使用'{{month.strftime('%B')}}'。请参阅http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior – liclac