from django import template
register = template.Library()
@register.simple_tag
def dictKeyLookup(the_dict, key):
# Try to fetch from the dict, and if it's not found return an empty string.
return the_dict.get(key, '')
from django import template
register = template.Library()
@register.simple_tag
def attributeLookup(the_object, attribute_name):
# Try to fetch from the object, and if it's not found return None.
return getattr(the_object, attribute_name, None)
OrderedDict字典类型支持破折号: https://docs.python.org/2/library/collections.html#ordereddict-objects
这似乎是实施OrderedDict的副作用。注意下面的键值对实际上是以集合的形式传入的。我敢打赌,OrderedDict的实现不会使用集合中传递的“密钥”作为真正的dict密钥,从而绕过这个问题。
因为这是OrderedDict实现的副作用,所以可能不是您想要依赖的东西。但它起作用了。
结果:
如果不想重新构造对象,自定义模板标记可能是唯一的方法。对于使用任意字符串键访问字典,this question的答案提供了一个很好的示例。
对于懒惰的人:
你这么用的:
如果要使用任意字符串名称访问对象的属性,可以使用以下命令:
你想用的是:
你甚至可以为子属性设计一些字符串分隔符(比如'\uuu'),但我把它留给家庭作业:-)
不幸的是,我想你可能走运了。从docs:
相关问题 更多 >
编程相关推荐