在使用for循环时,如何只打印一次“收到日期”? [英] How can I print the 'date received' only one time while using a for loop?

查看:161
本文介绍了在使用for循环时,如何只打印一次“收到日期”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按今天收到的消息,昨天收到的消息等对消息进行分组。为澄清起见,我尝试使用一个标有 Today的标头,然后在下面列出这些消息。我不是要打印今天以及当天收到的每条消息(目前正在发生这种情况)。

I am trying to group messages by received today, received yesterday, ect. To clarify, I am trying to have a single header that says "Today" and then list those messages underneath. I am NOT trying to print "Today" along with each message that was received on that day (which is currently what's happening).

我目前有TODAY和YESTERDAY标头在我的for循环内部,所以我知道这就是为什么要为每封邮件打印这些标头,但是如前所述,我只想打印一次。我的问题是,如何使用下面的代码实现这一目标?我是否需要针对每个时间段(今天,昨天,上周等)进行单独的for循环,还是有一种更有效的方法?

I currently have the TODAY and YESTERDAY headers inside of my for loop so I understand that is why it is printing these headers for each mail message, but as previously stated I just want to print them one time. My question is, how can I achieve this using the code below? Do I need to make separate for loops for each time period (today, yesterday, last week, ect.), or is there a more efficient way to do this?

{% for message in messages %}
    {% if message.date - current.date < 24 hours %}
        TODAY
        Sent by: {{ message.sender }}
        {{ message.body }}
    {% elif message.date - current.date > 24 hours and message.date - current.date < 48 hours %}
        YESTERDAY
        Sent by: {{ message.sender }}
        {{ message.body }
    {% endif %}
{% endfor %}


推荐答案

您可以使用 {{forloop.first}} 为此。因此,您的代码可以更新为

You can use {{forloop.first}} for this. So your code can be updated to

{% for message in messages %}
    {% if message.date - current.date < 24 hours %}
        {% if forloop.first %}
            TODAY
        {% endif %}
    {% elif message.date - current.date > 24 hours and message.date - current.date < 48 hours %}
       {% if forloop.first %}
        YESTERDAY
       {% endif %}
    {% endif %}

    Sent by: {{ message.sender }}
    {{ message.body }}

{% endfor %}

这篇关于在使用for循环时,如何只打印一次“收到日期”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆