displaying unique objects only in django templates

别等时光非礼了梦想. 提交于 2019-12-11 07:51:42

问题


I have a list of objects. I want to display these objects in such a way that only the first unique date displays if the subsequent objects contain the same date. If the date is different than it should display. Here is an example.

data:

  • id: 2, date: "01/01/2010"
  • id: 3, date: "01/01/2010"
  • id: 4, date: "02/02/2010"

What I want to display:

  • id - 2, "01/01/2010"
  • id - 3,
  • id - 4, "02/02/2010"

See how id 3 shows nothing since the previous date was the same?

How do I do this with django templates? One thing I tried was creating a custom filter. The only problem is that it uses a global variable which is a no-no in my opinion. How can I maintain state in a function filter or in django templating language to be concious of the previous value?

__author__ = 'Dave'
#This works but isn't best practice
from django import template
register = template.Library()

a = ''
@register.filter()
def ensure_unique(value):
    global a
    if a == value:
        return ''
    else:
        a = value
        return value

回答1:


Using a simple_tag made it much easier for me to save state and accomplish exactly what I needed to.

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def stop_repeat(context, event):
    """
    Finds various types of links embedded in feed text and creates links out of them.
    """
    if event.date:
        if (event.get_date_time_location(), event.id) in context:
            return ''
        else:
            context[(event.get_date_time_location(), event.id)] = (event.get_date_time_location(), event.id)
            return event.get_date_time_location()


来源:https://stackoverflow.com/questions/12501876/displaying-unique-objects-only-in-django-templates

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