仅在django模板中显示唯一对象 [英] displaying unique objects only in django templates
问题描述
数据:
- id:2,date: 01/01/2010
- id:3,date:01/01/2010
- id:4,date:02 / 02/2010
我想要显示的
- id - 2,01/01/2010
- id - 3,
- id - 4,02/02 / 2010
看到id 3自从以前的日期是一样的吗?
如何用django模板这样做?我尝试的一件事是创建一个自定义过滤器。唯一的问题是它使用一个全局变量,这在我看来是一个no-no。如何在一个函数过滤器或django模板语言中维护状态是否是先前的值?
__ author__ ='Dave '
#这是工作,但不是最佳做法
从django导入模板
register = template.Library()
a =''
@register .filter()
def ensure_unique(value):
全局a
如果一个==值:
return''
else:
a = value
返回值
使用simple_tag更容易为我保存状态,完成我所需要的。
从django导入模板
register = template。
@ register.simple_tag(Taking_context = True)
def stop_repeat(context,event):
查找嵌入的各种类型的链接
如果event.date:
if(even t.get_date_time_location(),event.id)在上下文中:
return''
else:
上下文[(event.get_date_time_location(),event.id)] =(event.get_date_time_location ),event.id)
return event.get_date_time_location()
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
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()
这篇关于仅在django模板中显示唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!