A custom template tag is probably the only way to go here if you don't want to restructure your objects. A good example for accessing dictionaries with an arbitrary string key is the answer to this question .
For the lazy:
from django import template register = template.Library() @register.simple_tag def dictKeyLookup(the_dict, key):
What do you use like this:
{% dictKeyLookup your_dict_passed_into_context "phone-number" %}
If you want to access the attribute of an object with an arbitrary string name, you can use the following:
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 not found return None. return getattr(the_object, attribute_name, None)
What would you like to use:
{% attributeLookup your_object_passed_into_context "phone-number" %}
You can even come up with some kind of string delimiter (like "__") for sub-attributes, but I will leave this for homework :-)
source share