诡异的自定义模板过滤器?
我在尝试同时在两个维度上迭代模板时遇到了麻烦。
基本情况解释如下:
http://www.djangobook.com/en/2.0/ Chapter04/(在苹果、香蕉索引示例中)
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
u'Item 2 is carrots.'
如果我想使用变量“fruitstep”从 1 迭代到 3,我无法在模板中执行此操作:
{{ items.fruitstep }} 失败并且考虑到长点链,这个概念将导致对模板的大量迭代要求。但我找不到执行此操作的标准方法,并且我不确定这是否是良好的模板实践。
因此,我创建了一个模板过滤器:
@register.filter
def key2value(collection,key):
try:
return collection[unicode(key)] # It seems that my collection
# keys are in unicode...
except:
return ""
这看起来是一个非常强大的过滤器。它一开始是一个非常具体的标签,但我想不出有什么理由不让它完全通用。
我想知道是否有一种标准方法可以做到这一点并且我已经重新发明了轮子,或者这段代码是否可以做一些可能危害系统的事情。
谢谢!
I was having trouble trying to iterate on a template on two dimensions at the same time.
The basic situation is explained here:
http://www.djangobook.com/en/2.0/chapter04/ ( in the apples, bananas indices example )
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
u'Item 2 is carrots.'
If I wanted to iterate from 1 to 3 on this with the variable "fruitstep", I cannot do it in a template:
{{ items.fruitstep }} fails and considering long dot chains, this concept would lead to massive iteration requirements on the template. But I couldn't find a standard way of doing it and I'm not sure it's good template practice.
So, I created a Template filter:
@register.filter
def key2value(collection,key):
try:
return collection[unicode(key)] # It seems that my collection
# keys are in unicode...
except:
return ""
This seems like an extremely powerful filter. It started off being a very specific tag, but I couldn't think of a reason not to make it completely generic.
I'm wondering if there is a standard way to do this and I've reinvented the wheel, or if this code could do something that can compromise the system.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有理由不在您自己的应用程序中执行此操作。我经常做类似的过滤器,并且实际上在这里发布了非常相似的代码来回答各种问题。
很难想象提供字典查找会损害系统。 Django 中默认不提供此功能,因为最初希望拥有一种受限制的模板语言 - 是否应该从一开始就提供此特定过滤器是有争议的,但鉴于没有提供,因此不太可能添加它现在。
No, there's no reason not to do this in your own application. I've often done similar filters, and have in fact posted very similar code here in answer to various questions.
It's hard to imagine a way in which providing dictionary lookup could compromise the system. This functionality isn't provided by default within Django because of the original desire to have a restricted template language - it's arguable whether this particular filter should have been provided from the start, but given that it wasn't, it's pretty unlikely to be added now.