我们已经建立了一个自定义的数据库,其中的许多属性被命名为含连字符的系统,即:如何从Django模板中访问包含连字符的字典键?
user-name
phone-number
这些属性不能在模板中访问如下:
{{ user-name }}
Django的投这是一个例外。我想避免必须转换所有的键(和子表键)才能使用下划线来解决这个问题。有更容易的方法吗?
我们已经建立了一个自定义的数据库,其中的许多属性被命名为含连字符的系统,即:如何从Django模板中访问包含连字符的字典键?
user-name
phone-number
这些属性不能在模板中访问如下:
{{ user-name }}
Django的投这是一个例外。我想避免必须转换所有的键(和子表键)才能使用下划线来解决这个问题。有更容易的方法吗?
如果您不想重构对象,自定义模板标记可能是唯一的途径。对于使用任意字符串键访问字典,this question的答案提供了一个很好的例子。
对于懒:
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, '')
你使用像这样:
{% dictKeyLookup your_dict_passed_into_context "phone-number" %}
如果你想用一个任意字符串名称访问对象的属性,你可以使用以下命令:
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)
你会喜欢哪一种:
{% attributeLookup your_object_passed_into_context "phone-number" %}
你甚至可以拿出某种形式的字符串分隔符的(如“__”)的子属性,但我会离开,对于功课:-)
OrderedDict字典类型支持破折号: https://docs.python.org/2/library/collections.html#ordereddict-objects
这似乎是实施OrderedDict的副作用。注意下面的关键值对实际上是作为集合传入的。我敢打赌,OrderedDict的实现不会使用集合中传递的“key”作为真正的词典关键,从而避免了这个问题。
由于这是OrderedDict实现的一个副作用,它可能不是你想要依赖的东西。但它的工作。
from collections import OrderedDict
my_dict = OrderedDict([
('has-dash', 'has dash value'),
('no dash', 'no dash value')
])
print('has-dash: ' + my_dict['has-dash'])
print('no dash: ' + my_dict['no dash'])
结果:
has-dash: has dash value
no dash: no dash value
我已经使用这个解决方案,但改变了它从一个标签到一个过滤器。它运作良好,谢谢! – jthompson
这绝对有效,但是如何访问包含字典作为值的字典中的密钥? – Kim