Django模板如何删除重复值?

2024-09-28 22:53:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法告诉Django隐藏/删除(显示空白)字段的值和前一行相同吗?在

例如:如果now对于不同的文章是相等的,那么它只能显示在第一组文章中吗?在

from django.views.generic.list import ListView
from django.utils import timezone

from articles.models import Article

class ArticleListView(ListView):

    model = Article

    def get_context_data(self, **kwargs):
        context = super(ArticleListView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context


<h1>Articles</h1>
<ul>
{% for article in object_list %}
    <li>{{ article.pub_date|date }} - {{ article.headline }}</li>
{% empty %}
    <li>No articles yet.</li>
{% endfor %}
</ul>

Article - now

a - 2017-01-01

b -

c - 2017-01-02

d -

这可以从查看还是直接在模板中实现?在


Tags: djangofromimportgetcontextarticle文章li
1条回答
网友
1楼 · 发布于 2024-09-28 22:53:52

您可以使用ifchanged,它:

Checks if a value has changed from the last iteration of a loop.

具体如下:

<h1>Articles</h1>
<ul>
{% for article in object_list %}
    <li>{{ article.headline }} - {% ifchanged article.pub_date|date %} 
        {{ article.pub_date|date }} {% endifchanged %}
   </li>
{% empty %}
    <li>No articles yet.</li>
{% endfor %}
</ul>

这将在每次迭代中检查article.pub_date的值,只有当该值发生变化时才会显示它。在

祝你好运:)

相关问题 更多 >