【问题标题】:django template print only first unique occurancedjango 模板只打印第一个唯一的出现
【发布时间】:2015-01-27 00:05:57
【问题描述】:

我有一个非常简单的任务要做,但我不知道如何在 django 模板中最有效地完成它。 基本上,这就是我想要完成的:

Jan. 27, 2015
    first post
    second post
    third post
Jan. 28, 2015
    another post
    and other
    etc
Feb. 18, 2015
    again
    and again

这可能是它的模型:

class Post(models.Model):
    date=models.DateField()
    name=models.CharField()

在views.py 中仅将查询集作为帖子传递:

Post.objects.filter(date__gte = date.today()).order_by("date")

然后在模板中使用 for 循环将其打印出来:

{% for post in posts%}
    {{post.name}}
{% endfor %}

如何只打印一次唯一日期?是否可以在模板中执行此操作,还是我必须在视图中处理它?我发现了类似的两岁大的post

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    有一个inbuilt template tag for that - regroup

    这并不完美,但通过文档应该可以让您接近。

    {% regroup posts by date as date_list %}
    
    <ul>
    {% for date in date_list %}
        <li>{{ date.grouper }}
        <ul>
            {% for item in date.list %}
              <li>{{ date.name }}</li>
            {% endfor %}
        </ul>
        </li>
    {% endfor %}
    </ul>
    

    【讨论】:

    • 太好了,谢谢!我发现 catavaran 的回答更容易,但也感谢您的回答!我应该早点考虑通过模板构建标签。
    【解决方案2】:

    可以使用{% ifchanged %}模板标签:

    {% for post in posts %}
        {% ifchanged %}<h3>{{ post.date }}</h3>{% endifchanged %}
        <div>{{ post.name }}</div>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      相关资源
      最近更新 更多