Jinja2 Group by Month/year

房东的猫 提交于 2020-12-28 20:53:15

问题


I'm trying to group a list of date/times in Jinja by month/year. Here's the code I have right now:

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

But the problem is that it currently groups by a specific date. I'd like to group by Month/Year (i.e. January 2011, February 2011 etc..).

Would it be more efficient to do this in Python instead?

thanks!


回答1:


You could first groupby('date.year') and then 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 %}


来源:https://stackoverflow.com/questions/12764291/jinja2-group-by-month-year

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!