如果您不想重组对象,那么自定义模板标签可能是唯一的选择。对于使用任意字符串键访问字典,此问题的答案提供了一个很好的示例。
对于懒惰的人:
from django import templateregister = template.Library()@register.simple_tagdef 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 templateregister = template.Library()@register.simple_tagdef 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" %}您甚至可以为子属性提供某种字符串分隔符(例如’__’),但我将其留给作业:-)



